1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91


# index() : 找出指定元素在列表中第一次出现的下标位置
list1 = [1, 2, 3, 4, 5, 3, 3, 3]
print(list1.index(3)) # 2
# print(list1.index(3, 3, 7)) # 5, 在下标3~7之间查找3第一次出现的下标位置
# print(list1.index(100)) # 报错
# ValueError: 100 is not in list
# 值错误: 100不在列表中

# 内置函数: Python提供的函数
list2 = [1, 2, 3, 4, 5]
print(max(list2)) # 最大值
print(min(list2)) # 最小值
print(sum(list2)) # 求和

# 排序
# sort() : 升序:从小到大
list3 = [3, 1, 2, 4, 7, 5, 11, 22, 16]
# list3.sort()
print(list3) # [1, 2, 3, 4, 5, 7, 11, 16, 22]

# 降序
list3.sort(reverse=True)
print(list3) # [22, 16, 11, 7, 5, 4, 3, 2, 1]

# 倒序/逆序/反转
list3 = [3, 1, 2, 4, 7, 5, 11, 22, 16]
list3.reverse()
print(list3) # [16, 22, 11, 5, 7, 4, 2, 1, 3]


# sorted() : 排序,但是不会改变原列表
list3 = [3, 1, 2, 4, 7, 5, 11, 22, 16]
list4 = sorted(list3)
print(list3) # [3, 1, 2, 4, 7, 5, 11, 22, 16]
print(list4) # [1, 2, 3, 4, 5, 7, 11, 16, 22]

# reversed() : 倒序, 但是不会改变原列表
list3 = [3, 1, 2, 4, 7, 5, 11, 22, 16]
list4 = reversed(list3)
print(list3) # [3, 1, 2, 4, 7, 5, 11, 22, 16]
print(list(list4)) # [16, 22, 11, 5, 7, 4, 2, 1, 3]


# 拷贝/复制

# 赋值
list5 = [1, 2, 3]
list6 = list5
list6[2] = 100
print(list5, list6) # [1, 2, 100] [1, 2, 100]

# 不可变类型 和 可变类型
# 基本类型 和 引用类型
# int,float,str,tuple 和 list, dict, set(使用很少)
# a = 10
# b = a
# b = 9
# print(a, b) # 10 9

# 复制/拷贝
# 浅拷贝/浅复制
list5 = [1, 2, 3]
list6 = list5.copy()
list6[2] = 100
print(list5, list6) # [1, 2, 3] [1, 2, 100]

# 深拷贝/深复制
list5 = [1, 2, 3, [4, 5]]
list6 = list5.copy() # 浅拷贝
list6[-1][-1] = 100
# list6[2] = 100
print(list5, list6) # [1, 2, 3, [4, 100]] [1, 2, 3, [4, 100]]

import copy
list5 = [1, 2, 3, [4, 5]]
list6 = copy.deepcopy(list5) # 深拷贝
list6[-1][-1] = 100
print(list5, list6) # [1, 2, 3, [4, 5]] [1, 2, 3, [4, 100]]


# 二维列表
list7 = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]