Python basic data types and basic operations
Article directory
1. Notes
One-line comment:
Single-line comments in Python #
begin with , for example:
# 这是一个注释
Multi-line comments:
Multi-line comments in Python are enclosed in three single quotes '''
or three double quotes """
, for example:
'''
这是多行注释,用三个单引号
这是多行注释,用三个单引号
这是多行注释,用三个单引号
'''
"""
这是多行注释,用三个双引号
这是多行注释,用三个双引号
这是多行注释,用三个双引号
"""
2. Basic data types
Summarize:
- Creating a variable in Python does not require first defining the variable type
- To view the data type of a variable use the function
type(x)
- Different types of elements can be stored in lists, tuples, and sets
- There is no long integer type in Pyhton3, the complex type is added
complex
z = a + bj
A number of the form is called a complex number, where a is the real part, b is the imaginary part, and j is the imaginary unit- Get the real part usage function
x.real
, get the imaginary part usage functionx.imag
, get the corresponding conjugate complex number usage functionx.conjugate()
Example:
# 整数
a = 10
print(type(a)) # <class 'int'>
# 浮点数
b = 3.18
print(type(b)) # <class 'float'>
# 字符串
c = "gaoqize"
print(type(c)) # <class 'str'>
# 列表
# 可以同时包含不同的类型
d = ["1", 2.3, 3]
print(type(d)) # <class 'list'>
# 元组
e = ("python", 12, 2.3)
print(type(e)) # <class 'tuple'>
# 字典
f = {
"key1":"v1", "key2":"v2"}
print(type(f)) # <class 'dict'>
# 集合
g = {
"python", 12, 2.3}
print(type(g)) # <class 'set'>
# 布尔型
h = True
print(type(h)) # <class 'bool'>
# 复数
i = 1 + 2j
j = 2 + 5j
print(type(i)) # <class 'complex'>
print(i + j) # (3+7j)
print(i - j) # (-1-3j)
print(i * j) # (-8+9j)
print(i.real) # 1.0
print(i.imag) # 2.0
print(i.conjugate()) # (1-2j)
Three, different types of conversion
Type (variable) to convert a variable to the corresponding type.
String to Integer Conversion
a = 10
var1 = str(a) # 整数转换成字符串
var2 = int(var1) # 字符串转换成整数
print(type(var1)) # <class 'str'>
print(type(var2)) # <class 'int'>
print(var1) # 10
print(var2) # 10
Integer and floating point conversion
a = 3.18
var1 = int(a) # 浮点数转换成整数
var2 = float(var1) # 整数转换成浮点数
print(type(var1)) # <class 'int'>
print(type(var2)) # <class 'float'>
print(var1) # 3
print(var2) # 3.0
Notice:
-
Converting floating point numbers to integers is done by removing the decimal point
-
Use the
round()
function to round to the corresponding number of decimal places, such as:var1 = round(2.366, 2) # 对2.366采用四舍五入的方式保留2位小数 print(var1) # 2.37
List and tuple conversion
d = ["1", 2.3, 3]
var1 = tuple(d) # 列表转换成元组
var2 = list(var1) # 元组转换成列表
print(type(var1)) # <class 'tuple'>
print(type(var2)) # <class 'list'>
print(var1) # ('1', 2.3, 3)
print(var2) # ['1', 2.3, 3]
Convert nested tuples to dictionaries
e = (("name", "gaoqize"), ("sex", "man")) # 嵌套元组,如果要转换成字典,被嵌套元组只能含有2个元素
var1 = dict(e) # 嵌套元组转换成字典
print(type(e)) # <class 'tuple'>
print(type(var1)) # <class 'dict'>
print(e) # (('name', 'gaoqize'), ('sex', 'man'))
print(var1) # {'name': 'gaoqize', 'sex': 'man'}
Converting different bases to each other
Example:
x must be of type string
If you want to convert other bases into bases other than base 10, you must first convert them to base 10.
int("x", 2)
Convert the binary x to the corresponding decimal
bin(int("x", 8))
Convert the x in octal to the corresponding binary
print(int("1000", 2)) # 8print(bin(int("8", 10))) # 0b1000
Fourth, the operation of strings
Strings in Python support single quotes, double quotes, and triple quotes (multi-line strings are supported) (Java only supports double quotes)
define string
var1 = 'str1'
var2 = "str2"
var3 = '''line1
line2'''
print(var1, var2, var3)
'''
str1 str2 line1
line2
'''
concatenate strings
Use the "+" sign for splicing
var1 = 'str1'
var2 = "str2"
print(var1 + var2) # str1str2
Copy multiple strings
string * times
var1 = 'str1' * 10
print(var1) # str1str1str1str1str1str1str1str1str1str1
split string
- By default, spaces are split (multiple spaces are split as one space)
- The character to be split is specified in the parameter
var2 = "str1 str2 str3 str4str5"
print(var2.split()) # ['str1', 'str2', 'str3', 'str4str5']
print(var2.split(' ')) # ['str1', 'str2', '', 'str3', '', '', 'str4str5']
var3 = "str1:str2:str3:str4"
print(var3.split(':')) # ['str1', 'str2', 'str3', 'str4']
replace string replace
var4 = "I love Python"
print(var4.replace("Python", "Java")) # I love Java
print(var4) # I love Python,也就是说原字符串并没有发生改变
String case conversion
var5 = "GAOQIZE"
print(var5.upper()) # GAOQIZE
print(var5.lower()) # gaoqize
print(var5.capitalize()) # Gaoqize,让首字母大写,其余字母小写
Convert list to string
Use the join
function to complete the operation of converting the list into a string, pay attention to the character by which the elements in the list are connected together
var6 = ["I", "love", "u"]
# 列表中的元素通过","进行拼接
print(",".join(var6)) # I,love,u
Five, the operation of the list
- The specific operations of concatenating lists and copying multiple lists are the same as strings.
- Lists can also be nested, as in
list1 = ["hello", 12, 12.8, ["hi", 22]]
Access list elements by index
Similar to an array, the corresponding element can be accessed directly by using the index.
Front-to-back access to index positions starts at 0, and back-to-front access to index positions starts from -1.
list1 = ["hello", 12, 12.8, ["hi", 22]]
print(list1[0]) # hello
print(list1[-1]) # ['hi', 22]
Access list elements by sharding
The position of the index uses [x:y]
the format, note that it is closed on the left and open on the right .
[x:]
Represents all elements after the x position (including x) , and [:y]
represents all elements before the y position (excluding y) .
list1 = ["hello", 12, 12.8, ["hi", 22]]
print(list1[0:2]) # ['hello', 12]
print(list1[-3:-1]) # [12, 12.8]
print(list1[0:]) # ['hello', 12, 12.8, ['hi', 22]]
print(list1[:3]) # ['hello', 12, 12.8]
Access list elements in equal steps
Use [::x]
means to visit the first element first, and then visit the next element with step x in turn.
list1 = ["hello", 12, 12.8, ["hi", 22]]
print(list1[::3]) # ['hello', ['hi', 22]]
print(list1[::1]) # ['hello', 12, 12.8, ['hi', 22]]
print(list1[::2]) # ['hello', 12.8]
add list element
Use append()
to add a single element to the end of the list.
list1 = ["hello"]
list1.append("你好")
print(list1) # ['hello', '你好']
Use extend()
to add a list to the end of the list.
list1 = ["hello", 12, 12.8]
list2 = ["more"]
list1.extend(list2)
print(list1) # ['hello', 12, 12.8, 'more']
Note: Using append()
Add Element will create a new list, using extend()
Add Element will add on the basis of the original list.
Use insert()
to add an element to the list at the specified position.
list1 = ["hello", 12, 12.8]
list1.insert(0, "first") # 在0位置插入一个元素
print(list1) # ['first', 'hello', 12, 12.8]
remove element from list
Use to del list[x]
delete the element at index position x.
list1 = ["hello", 12, 12.8]
del list1[0]
print(list1) # [12, 12.8]
Use to pop()
pop the last element of the list.
list1 = ["hello", 12, 12.8]
print(list1.pop()) # 12.8
Count the number of occurrences of an element in a list
Use count()
to get the number of occurrences of an element.
list1 = ["hello", 12, 12.8, 12]
print(list1.count(12)) # 2
6. Operations on tuples
The biggest difference between a tuple and a list is that once a tuple is created, the elements in it cannot be changed. Once a change occurs, a new tuple is created.
The rest of the operations are almost the same as lists.
Seven, the operation of the dictionary
Merge multiple dictionaries
Use to update
complete the merging or updating of the dictionary: the same key is updated, and different keys are merged.
dict1 = {
"k1":"v1", "k2":"v2"}
dict2 = {
"k1":"update_k1", "k3":"v3"}
dict1.update(dict2)
print(dict1) # {'k1': 'update_k1', 'k2': 'v2', 'k3': 'v3'}
Get the corresponding value by key
Use the dictionary name ["key"] to get the value of the corresponding key in the dictionary.
dict1 = {
"k1":"v1", "k2":"v2"}
print(dict1["k1"]) # v1
Add a new key-value pair
Add a new key-value pair to this dictionary using dictionaryname["key"] = "value". (If the key already exists, update the value of the key)
dict1 = {
"k1":"v1", "k2":"v2"}
dict1["k3"] = "v3"
print(dict1) # {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}
Eight, the operation of the set
Elements in a collection are not repeatable.
Create an empty collection:
var1 = {
} # 一对大括号创建一个空的字典
var2 = set() # 固定格式创建空的集合
print(type(var1)) # <class 'dict'>
print(type(var2)) # <class 'set'>
union
var1 = {
"gao", 12, 3.16}
var2 = {
"new", "gao"}
print(var1.union(var2)) # {3.16, 'new', 'gao', 12}
# 会自动去掉重复的元素
intersection
var1 = {
"gao", 12, 3.16}
var2 = {
"new", "gao"}
print(var1.intersection(var2)) # {'gao'}
Complement
var1 = {
"gao", 12, 3.16}
var2 = {
"new", "gao"}
print(var1.difference(var2)) # {3.16, 12}
Is it a subset
var1 = {
"gao", 12, 3.16}
var2 = {
"gao"}
print(var2.issubset(var1)) # True
Nine, basic operators
Perform operations on integers and floating-point numbers, and the result is a floating-point number.