Python seven data types

overview

Python data types are mainly divided into the following seven categories:

Numbers (number)
Boolean (Boolean)
String (string)
List (list)
Tuple (tuple)
Dictionary (dictionary)
Set (collection)

Among Python's seven standard data types:

Immutable data types (4): Number (number), Boolean (Boolean), String (string), Tuple (tuple); variable
data types (3): List (list), Dictionary (dictionary), Set (collection).

The contents of mutable data types can change as the function executes, while immutable data types cannot.

Q: How to determine the type of a variable?

Answer: ① Use the type (variable name) method to return the data type of the variable ② isinstance (variable name, data type), which can only return True or False (true or false)

1. Number type (Numbers)

Numerical types are numbers in our daily life

Python's numeric types include:

int (long integer)
float (floating point type)
complex (complex number)

# 整型int,浮点型float
a=1
b=1.1
print(a,b,type(a),type(b),isinstance(a,int))
#输出结果为
#1 1.1 <class 'int'> <class 'float'> True

2. Boolean type (Boolean)

The Boolean type is a data type related to logic, with only two values: True (true) and False (false)

Among them, boolean type values ​​can be added, but once added, the type will be converted to int type

# 2.布尔型Boolean
c=True
d=False
d=c+d
print(type(c),type(d),d)
#输出结果
#<class 'bool'> <class 'int'> 1

3. String type (String)

In the Python variable definition, if the content of its assignment is enclosed by single or double quotation marks, it is the string str type.

String manipulation:

1. String index

a[i] represents the index of the i+1th position of the string a, and a[-1] represents the index of the last position of the string a

2. String interception

s=a[i:j], where i and j can be omitted, which means starting from position i to ending at position j, and the intercepted string does not include position j

3. String splicing: "+"

4. String multiplexing: "*"

# 3.字符串str
f='我是小高'
g=',你呢'
print(f[0],f[-1],f[:3],f[1:-1],f+g,f*3)
# 我 高 我是小 是小 我是小高,你呢 我是小高我是小高我是小高

4. List type (List)

Python's list can complete the data structure implementation of most collection classes. It supports characters, numbers, strings and even lists (that is, nested or multidimensional lists, which can be used to represent multidimensional arrays).

Array operations are similar to string types

Multidimensional array initialization:

[…[[[0 for i in range(x)] for j in range(y)] for k in range(z)]…]

# 4.列表list
e=[1,2,3,"a"]
list=["b",'c']
print(type(e),e[2],e[2:-1],e+list,list*2)
#<class 'list'> 3 [3] [1, 2, 3, 'a', 'b', 'c'] ['b', 'c', 'b', 'c']
# 3*2二维数组初始化
list2=[[0 for i in range(2)] for j in range(3)]
#[[0, 0], [0, 0], [0, 0]]

5. Tuple type (Tuple)

Python's tuples are similar to list lists, and tuples are identified by (). Inner elements are separated by commas. But tuples cannot be assigned twice, which is equivalent to a read-only list.
It supports all types of characters, numbers, strings, lists, tuples, etc.
The value, interception, connection, and repetition of tuples are the same as lists

# 5.元组tuple
a=1
b=True
c='aaa'
g=(1,2,3,4)
print(type(g),g)
g=(a,b,c,g)
print(g)
#<class 'tuple'> (1, 2, 3, 4)
#(1,True,'aaa',(1, 2, 3, 4))

Although the elements of a tuple are immutable, it can contain mutable objects (the aforementioned mutable data), such as lists.

a=[1,2,3]
tuple=(1,2,a)
print(tuple)
a[1]=4
print(tuple)
#(1, 2, [1, 2, 3])
#(1, 2, [1, 4, 3])

6. Collection type (Set)

A set (set) is composed of one or several wholes of different sizes, and the things or objects that make up the set are called elements or members

The basic function is to perform membership tests and remove duplicate elements

Sets can be created using curly braces { } or the set() function,

Note: To create an empty collection, you must use set() instead of { }, because { } is used to create an empty dictionary

Data of variable data types cannot be added to the collection

# 6.集合set
h={
    
    'a',"b",1,(1,2),"hishis"}
print(type(h),h)
se=set()
print(type(se))
# <class 'set'> {1, (1, 2), 'a', 'b', 'hishis'}
# <class 'set'>

7. Dictionary type (Dictionary)

Dictionary (dictionary) is the most flexible built-in data structure type in python except list; list is an ordered collection of objects, dictionary is an unordered collection of objects; dictionary is identified by "{ }"; dictionary is composed of index (key) and Its corresponding value value composition

Dictionary value, the elements in the dictionary are accessed by key, not by offset

Keys must use immutable types (numbers, booleans, strings, tuples)

In the same dictionary, the key (key) must be unique

# 7.字典dict
a=1
b=True
c=[1,2,3]
d=(1,2)
e='aaa'
i={
    
    "a":a,"b":b,"c":c,"d":d,"e":e,'i':"xiaogao"}
print(type(i),i)
#<class 'dict'> {'a': 1, 'b': True, 'c': [1, 2, 3], 'd': (1, 2), 'e': 'aaa', 'i': 'xiaogao'}
i['a']=False#可以改变原有数据类型
print(i.keys())
print(i.values())
print(i)
# dict_keys(['a', 'b', 'c', 'd', 'e', 'i'])
# dict_values([False, True, [1, 2, 3], (1, 2), 'aaa', 'xiaogao'])
# {'a': False, 'b': True, 'c': [1, 2, 3], 'd': (1, 2), 'e': 'aaa', 'i': 'xiaogao'}

type comparison

Comparison of lists, tuples, dictionaries, sets:

List[] (list): An ordered mutable collection that allows duplicate data.
Tuple ( ) (tuple): An ordered immutable collection that allows duplicate data.
Collection { } (set): Unordered and unindexed (the index is a key value) collection, no duplicate data.
Dictionary { } (dictionary): unordered, mutable, indexed collection, no duplicate data.

type conversion


Attributes explain
int(x) Convert x to an integer and round down
float(x) Convert x to a float
complex(x [,imge]) convert x to a complex number
str(x) convert x to a string
repr(x) Convert the object x to an expression string
eval(x) Used to calculate a valid Python expression in a string and return an object, in fact, it can calculate a string expression and get the result
tuple(s) Convert the sequence s to a tuple
list(s) converts the sequence s into a list
set(s) Convert the sequence s into a mutable collection, which can be used to deduplicate the list
dict() create a dictionary
frozenset(s) converts s to an immutable collection
chr(x) Convert an integer to its ASCIIi character
dict() create a dictionary
hex(x) Convert an integer to a hexadecimal string
oct(x) converts an integer to an octal string
ord(x) Convert a character to an integer, which is the ASCII code corresponding to x

Guess you like

Origin blog.csdn.net/qq_42076902/article/details/124728367