列表的使用(包括copy和deepcopy)

列表的切片

names = ["张三","李四","王五","隔壁老王"]
print(names[0],names[2]) #张三 王五
print(names[1:3]) #['李四', '王五']
print(names[-2:]) #['王五', '隔壁老王']
print(names[0:3]) #['张三', '李四', '王五']

列表添加数据

names = ["张三","李四","王五","隔壁老王"]
names.append("小东")
print(names) #['张三', '李四', '王五', '隔壁老王', '小东']

列表的insert

names = ["张三","李四","王五","隔壁老王"]
names.insert(1,"xiaolei") #['张三', 'xiaolei', '李四', '王五', '隔壁老王']
names.insert(3,"wei") #['张三', '李四', '王五', 'wei', '隔壁老王']
print(names)

列表的删除元素

方法一

names = ["张三","李四","王五","隔壁老王"]
names.pop(1)
print(names)

方法二

del names[1]
print(names)

方法三

names.remove("张三")
print(names)

列表元素的修改

names = ["张三","李四","王五","隔壁老王"]
names[2] = "xiaolei"
print(names)

列表的反序

names = ["张三","李四","王五","隔壁老王"]
names.reverse()
print(names)

列表的元素统计

names = ["张三","李四","王五","隔壁老王","李四","王五"]
print(names.count("王五")) # 2

列表deepcopy和copy

copy

import copy
names = ["张三","李四",["alex","jack"],"王五","隔壁老王"]
name2 = copy.copy(names)
names[1] = "xiaolei"
names[2][0] = "WORD"
print(names,"\n",name2)

运行结果

列表的使用(包括copy和deepcopy)_第1张图片

deepcopy

import copy
names = ["张三","李四",["alex","jack"],"王五","隔壁老王"]
name2 = copy.deepcopy(names)
names[1] = "xiaolei"
names[2][0] = "WORD"
print(names,"\n",name2)

运行结果

列表的使用(包括copy和deepcopy)_第2张图片

添加解释

如果copy.copy拷贝的是元组,那么他不会进行浅拷贝,仅仅是指向。

原因:因为元组是不可变类型,那么意味着数据一定不能修改,因此用copy.copy的时候他会自动判断,是元组时自动指向它。

你可能感兴趣的:(列表的使用(包括copy和deepcopy))