[Python Basics] Seven data types in Python

leading

The data types in Python mainly include: Number(数字), Boolean(布尔), String(字符串), List(列表), Tuple(元组), Dictionary(字典), Set(集合).

It is further divided into variable data types and immutable data types. Variable data types refer to 可以随着函数的执行发生变化,而不可变数据类型不可以改变
immutable data types (3): Number(数字), Boolean(布尔), , String(字符串)and Tuple(元组)
variable data types (4): , List(列表),Dictionary(字典)Set(集合)

Q: How to determine the type of a variable?
Answer: 1. You can use the type (variable name) method to return the data type of the variable; 2. isinstance (variable name, data type) can only return True or False

1. Number type (Number)

There are 3 data types in Python3: int (integer), float (floating point), complex (complex number).
The integer type of Python 3 has no size limit and can be used as a Long type, and bool is a subtype of the integer type.

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

Two, Boolean type (Boolean)

The Boolean type is a data type related to logic, and has only two values ​​​​True and False. (Note: Boolean values ​​can be added, and the type will be converted to int type after addition)

# 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, the value enclosed by single quotes and double quotes is the string str type.

3.1 String Index

insert image description here
The positive index a[i] of the string starts from 0 to represent the first character, and the negative index a[-1] starts from -1 to represent the character at the end of the string.

3.2 String interception, splicing and multiplexing

a = b[begin, end, step], begin means the start position, the default is 0, end means the end position, the default is variable length, step means the step size, the default is 1. For example: a【i,j】, means starting from position i to ending at position j, where the intercepted character string does not include position j.
Note : The use of a negative index in a slice does not mean fetching from end to head, the index just limits the range of data fetching.
步长It is to determine the reading order. If the step size is a negative number, it is read from the end to the beginning, and if it is a positive number, it is read from the beginning to the end.

str1 = "hello,world!"
print(str1[::])
print(str1[2:5])
print(str1[2,6,2])
print(str1[-1:-4])
print(str1[-5:-2])
print(str1[-1:-5:-1])

# 输出结果
hello,world!
llo
lo
空
orl
!dlr
a = "我是王菜鸟"
b = ",你呢"
print(a[0],a[-1],a[:3],a[1,-1],a+b,a*2)

# 输出结果
我 鸟 我是王 是王菜 我是王菜鸟,你呢 我是王菜鸟我是王菜鸟

Fourth, the list type (List)

A list is a frequently used data type, and its elements can be custom objects such as strings, numbers, lists, and tuples. The list is defined by [], a collection separated by English commas, and the elements can be repeated.

The operations in the list usually contain 索引, 切片, in和not in, len, 操作符+和*, 添加/删除/查询元素, , 排序和反转. Indexing and slicing of lists are consistent with strings, so we won’t repeat them here.将元组、字符串等序列转换成列表(不会修改原有的序列)

Next, some operations in the list will be introduced:

4.1 in和not in

Determine whether a value exists in the list, if it exists, return True, otherwise return False (note: existence means the same as an element of the list).

store = [[65, 33], '女', 'wang', 24, 2.3]
print("wang" in store)
print("33" in store)
print("女" not in store)

# 输出结果
True
False
False

4.2 len()

The len() method returns the number of elements in the list

store = [[65, 33], '女', 'wang', 24, 2.3]
print(len(store))

# 输出结果
5

4.3 Add/delete/query elements

Add/remove/query elements
operate method describe
add element append(obj) Append an element to the list, that is, add a specified element at the end of the list
extend(iterable) Append multiple elements to the list, that is, add multiple elements at the end of the list, iterable is a sequence, indicating the sequence of elements to be added
insert(index, obj) Insert an element at the specified position in the list (elements at and after the specified position are moved backward by one subscript)
delete element pop(index) Delete and return the element at the specified index in the list, index defaults to -1, which is the last element
remove(element) Deletes the first element that matches the specified value (does not return related values)
of the remove list elements or the entire list
clear() Delete all elements in the list, that is, after success, the list is an empty list
query element index(value, start=None, stop=None) Find the index position of the first match with the specified value from the specified range in the list (start and stop cannot pass parameters based on keywords)
count(obj) Count the number of times an element appears in a list

add element

# append
store = [[65, 33], '女', 'wang', 24, 2.3]
store.append("王菜鸟")
print(store)
store.append([66, 68])
print(store)

# extend
store.extend(["Kevin",168])
print(store)

# insert
store.insert(2,999)
print(store)


# 输出结果
[[65, 33], '女', 'wang', 24, 2.3, '王菜鸟']
[[65, 33], '女', 'wang', 24, 2.3, '王菜鸟', [66, 68]]
[[65, 33], '女', 'wang', 24, 2.3, '王菜鸟', [66, 68], 'Kevin', 168]
[[65, 33], '女', 999, 'wang', 24, 2.3, '王菜鸟', [66, 68], 'Kevin', 168]

delete element

print(store.pop(2))
store.remove('Kevin')
print(store)
store.clear()
print(store)

# 输出结果
999
[]
[]

query element

store = [[65, 33], '女', 'wang', 24, 2.324]
print(store.index('女'))
print(store.count(24))

# 输出结果
1
2

4.4 sort (sort) and reverse (reverse)

sort (sort) :

Format: list.sort(key=None, reverse=False)
key – specifies a function with one parameter and returns an object, which is used to extract the content to be compared from the elements in the list.
sort() sorts in ascending order by default, ie reverse= False, descending reverse=True

list1 = [22, 11, 25, 98, 72, 68, 49]
list1.sort()
print(list1)
list1.sort(reverse=True)
print(list1)

# 输出结果
[11, 22, 25, 49, 68, 72, 98]
[98, 72, 68, 49, 25, 22, 11]

注意:sort中key参数的用法

# 按照总分成绩降序排名
list1 = [[97, 54, 93], [59, 78, 83], [44, 64, 97], [83, 79, 73]]
def sum_scores(scores):
    return scores[0] + scores[1] + scores[2]
    
list1.sort(key=sum_scores, reverse=True)
print(list1)

# 输出结果

Reverse (reverse)
reverse: sorting rules, reverse = True descending order, reverse = False ascending order (default).

list1 = [22, 11, 25, 98, 72, 68, 49]
list1.reverse()
print(list1)

# 输出结果
[49, 68, 72, 98, 25, 11, 22]

4.5 list()

Convert sequences such as tuples and strings into lists (the original sequence will not be modified).

# 元组
tup = (22, 86, 26, 35)
print(list(tup))
print(tup)

# 字符串
str1 = "Happy New Year"
print(list(str1))
print(str1)

# 输出结果
[22, 86, 26, 35]
(22, 86, 26, 35)

['H', 'a', 'p', 'p', 'y', ' ', 'N', 'e', 'w', ' ', 'Y', 'e', 'a', 'r']
Happy New Year

Five, set (Set)

Set Set is an unordered and non-repeatable sequence, use {}or set()function to create, if you want to create an empty set, you must use set(), { } is used to create an empty dictionary .
Note : Sets only store immutable data types, such as Numbers, strings, tuples, etc., but cannot store variable data types such as lists, dictionaries, and sets.

set1 = set({
    
    "Kevin", "Lucy", "Toke", 24})
print(set1)

set2 = set("wang")
print(set2)

set3 = set({
    
    22, 33})
print(set3)

# 输出结果
{
    
    'Toke', 24, 'Lucy', 'Kevin'}
{
    
    'w', 'g', 'n', 'a'}
{
    
    33, 22}

6. Dictionary type (Dictionary)

Dictionaries store objects in key-value pairs (key: value).
1. The key (key) must be unique in the dictionary, and the key is an immutable data type, such as string, number, and tuple. If the key is assigned multiple values ​​at creation time, the last value is stored.
2. The value (value) can be any object, such as None, numeric value, string, dictionary, etc.

dict1 = dict()
print(len(dict1), type(dict1))

dict2 = {
    
    }
print(len(dict2), type(dict2))

# 如果创建时键被赋值多次,最后一个值才被存储
dict3 = {
    
    "a": "Kevin", "b": "Lucy", "a": "Toke"}
print(dict3)

# 输出结果
0 <class 'dict'>
0 <class 'dict'>
{
    
    'a': 'Toke', 'b': 'Lucy'}

7. Others

7.1 Deep copy and shallow copy

Python provides deep copy and shallow copy methods for data types such as lists, sets, and dictionaries.
Shallow copy: copy the address of the data, the copy() method just adds a pointer to the object, and does not allocate new space to store data; deep copy: allocate new space to store data
, the original data and the data after deep copy does not affect

function describe
iterable.copy() Returns a shallow copy of the iterable object iterable data
copy.deepcopy(iterable) Returns the deep copy data of the iterable object iterable

If you understand it from a relatively simple point of view, shallow copy and deep copy are the difference between nested objects. For the modification of the nested object of the original data, the nested object corresponding to the shallow copy will be affected synchronously, and the deep copy will not be affected. Influence.
From the perspective of storage, shallow copy is to increase the storage address of the value pointed to by the pointer, and does not open up a new memory space for storing the value, while deep copy is to open up a new memory space to store and point the pointer to the new memory address.

7.2 Type comparison

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.

Guess you like

Origin blog.csdn.net/qq_44723773/article/details/128679577