插入
names = ["zhangyang", "gunyun", "xiangpeng", "xuliangchen"]
#将chenyunfei插入到gunyun前面
names.insert(1, "chenyunfei")#"1"是想插入的位置
print(names)
删除
names = ["zhangyang", "gunyun", "xiangpeng", "xuliangchen"]
#第一种方法
names.remove("gunyun")
#第二种方法
del names[1]
返回列中元素的位置
names = ["zhangyang", "gunyun", "xiangpeng", "xuliangchen"]
print(names.index("gunyun"))
统计列表中相同元素的个数
names = ["zhangyang", "gunyun", "xiangpeng", "xuliangchen"]
names.append("gunyun")
print(names.count("gunyun"))
copy操作:浅拷贝(第二个列表中的每一个元素只是第一个列表中每个元素的一个引用),只拷贝了第一层列表
浅拷贝的三种方式:
person = ['name', ['saving', 100]]
p1 = copy.copy(person)
p2 = person[:]
p3 = list(person)
names = ["zhangyang", "gunyun", "xiangpeng", "xuliangchen"]
name2 = names.copy()
print(names)
print(name2)
names[0] = "张扬"
print(names)
print(name2)
names = ["zhangyang", "gunyun", "xiangpeng", "xuliangchen",["chen", "yun"]]
name2 = names.copy()
print(names)
print(name2)
#这次打印的话,name2中子列表中的值也发生了对应的话,这是因为在copy的时候,第一层拷贝的是值,对于子列表,可以认为拷贝的是指针,那么在打印的时候,当打印到name2的子列表时,就会去访问这个指针所指向的内存中存储的内容,所以就发生了变化
names[4][0] = 'CHEN'
print(names)
print(name2)
['zhangyang', 'gunyun', 'xiangpeng', 'xuliangchen']
['zhangyang', 'gunyun', 'xiangpeng', 'xuliangchen']
['张扬', 'gunyun', 'xiangpeng', 'xuliangchen']
['zhangyang', 'gunyun', 'xiangpeng', 'xuliangchen']
['zhangyang', 'gunyun', 'xiangpeng', 'xuliangchen', ['chen', 'yun']]
['zhangyang', 'gunyun', 'xiangpeng', 'xuliangchen', ['chen', 'yun']]
['zhangyang', 'gunyun', 'xiangpeng', 'xuliangchen', ['CHEN', 'yun']]
['zhangyang', 'gunyun', 'xiangpeng', 'xuliangchen', ['CHEN', 'yun']]
浅拷贝在其中一个地方很有用:
import copy
#person当做模板
person = ['name', ['saving', 100]]
#用person模板生成p1和p2,假设p1和p2具有夫妻关系,他们具有一个相同的银行账号
p1 = person[:]
p2 = person[:]
p1[0] = 'alex'
p2[0] = 'fengjie'
print(p1)
print(p2)
p1[1][1] = 50
print(p2)
result:
['alex', ['saving', 100]]
['fengjie', ['saving', 100]]
['fengjie', ['saving', 50]]
深拷贝
import copy
names = ["zhangyang", "gunyun", "xiangpeng", "xuliangchen"]
name2 = copy.deepcopy(names)
print(names)
print(name2)
names[0] = "张扬"
print(names)
print(name2)
names = ["zhangyang", "gunyun", "xiangpeng", "xuliangchen",["chen", "yun"]]
name2 = copy.deepcopy(names)
print(names)
print(name2)
names[4][0] = 'CHEN'
print(names)
print(name2)
['zhangyang', 'gunyun', 'xiangpeng', 'xuliangchen']
['zhangyang', 'gunyun', 'xiangpeng', 'xuliangchen']
['张扬', 'gunyun', 'xiangpeng', 'xuliangchen']
['zhangyang', 'gunyun', 'xiangpeng', 'xuliangchen']
['zhangyang', 'gunyun', 'xiangpeng', 'xuliangchen', ['chen', 'yun']]
['zhangyang', 'gunyun', 'xiangpeng', 'xuliangchen', ['chen', 'yun']]
['zhangyang', 'gunyun', 'xiangpeng', 'xuliangchen', ['CHEN', 'yun']]
['zhangyang', 'gunyun', 'xiangpeng', 'xuliangchen', ['chen', 'yun']]