# append() 在列表的最后添加一个数据
list1 = ["上海","城隍庙","北京"]
list1.append("糖葫芦")
# print(list1)
list1 = []
for i in range(5):
if i % 2 == 0:
list1.append(i)
print(list1)
# insert() 在列表的指定索引之前添加数据
list1 = ["王涛","曹文禹","李之晨"]
list1.insert(2,"邓克胜")
print(list1)
# pop() 在列表的指定索引位置删除数据
list1 = ["喜羊羊","青青草原","我最狂","dj狼"]
list1.pop() # 不写参数,默认是删除最后一个数据
print(list1)
# 根据索引删除值
list1.pop(1)
print(list1)
# remove() 在列表中删除指定数据
list2 = ["马杀鸡","spa","泰式按摩","踩背","大宝剑"]
list2.remove("spa")
print(list2)
list3 = list2[:] # 浅拷贝
for i in list2:
list3.remove(i)
print(list3)
# clear() 清空列表
list2 = ["马杀鸡","spa","泰式按摩","踩背","大宝剑"]
list2.clear()
print(list2)
# copy() 复制列表
list2 = ["马杀鸡","spa","泰式按摩","踩背","大宝剑"]
list1 = list2.copy() # 浅拷贝
print(list1)
# 定义变量, 赋值
a = [1,2,3,4]
b = a
b[0] = 2
print(b)
print(a)
# 拷贝
# 浅拷贝
a = [1,2,3,4]
b = a.copy()
b[0] = 2
print(b)
print(a)
# 第二种浅拷贝
b = a[:]
a[0] = 2
print(b)
print(a)
# 第三种浅拷贝
import copy
b = copy.copy(a)
a[0] = 2
print(a)
print(b)
# 浅拷贝 只对父级元素拷贝的
list1 = [1,2,[3,4]]
list2 = list1.copy()
list1[2][0] = 5
print(list1)
print(list2)
# 深拷贝:拷贝的是对象本身,是一个单独的对象,只是值和原对象一样而已
import copy
list1 = [1,2,[3,4,[5,6]]]
list2 = copy.deepcopy(list1)
list1[2][2][1] = 7
print(list1)
print(list2)
# count() 计算列表中指定数据出现的次数,不存在则返回0
list1 = ["张文广","兄弟连","帅","帅","帅哥"]
res = list1.count("帅比")
print(res)
# extend() 将2个列表合并位1个
list1 = [1,2,3]
list2 = [4,5,6]
list2.extend(list1)
print(list2)
# reverse() 列表反转
list1 = ["python","java","php","h5"]
list1.reverse()
print(list1)
# sort() 列表排序(用法和sorted一样) 对原列表直接改变
list1 = [1,4,2,5,7,3]
list1.sort(key=lambda x:x%2)
print(list1)
# index() 获取某个值在列表中的索引
list1 = [1,2,3,2,4,5]
res = list1.index(2)
print(res)
python_深浅copy
最新推荐文章于 2023-07-10 09:11:08 发布