python学习
- python里面的列表复制
import copy
a = [0,1,2,[3,2],4]
b = copy.deepcopy(a)
c = a
d = list(a)
e = copy.copy(a)
f = a[:]
a[0] = 100
f[3] = [888,666]
b[3][0] = 99
print(a)
print(b)
print(c)
print(d)
print(e)
print(f)
[100, 1, 2, [3, 2], 4]
[0, 1, 2, [99, 2], 4]
[100, 1, 2, [3, 2], 4]
[0, 1, 2, [3, 2], 4]
[0, 1, 2, [3, 2], 4]
[0, 1, 2, [888, 666], 4]
这其中只有copy.deepcopy()是深复制,也就是这样复制的话,得到的新列表和原来的列表没有任何关系,修改其中一个,另一个并不会改变。
2.列表操作练习
lst = [2,5,6,7,8,9,2,9,9]
lst.append(15)
print(lst)
lst.insert(int(len(lst)/2), 20)
print(lst)
lst.extend([2,5,6])
print(lst)
del lst[3]
print(lst)
lst.reverse()
print(lst)
lst.sort()
print(lst)
lst.sort(reverse = True)
print(lst)
[2, 5, 6, 7, 8, 9, 2, 9, 9, 15]
[2, 5, 6, 7, 8, 20, 9, 2, 9, 9, 15]
[2, 5, 6, 7, 8, 20, 9, 2, 9, 9, 15, 2, 5, 6]
[2, 5, 6, 8, 20, 9, 2, 9, 9, 15, 2, 5, 6]
[6, 5, 2, 15, 9, 9, 2, 9, 20, 8, 6, 5, 2]
[2, 2, 2, 5, 5, 6, 6, 8, 9, 9, 9, 15, 20]
[20, 15, 9, 9, 9, 8, 6, 6, 5, 5, 2, 2, 2]
3.修改列表
lst = [1,[4,6],True]
lst[0] *= 2
lst[1][0] *= 2
lst[1][1] *= 2
lst[2] *= 2
print(lst)
[2, [8, 12], 2]