马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
也用了切片了也用了元组了,就是没效果,求大神给支招!
- lst = [[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0]]
- lst1 = lst[:]
- lst[0][1] = 1
- if lst1 == lst:
- print("未改变",1)
- else:
- print("已改变",1)
- tuple2 = tuple(lst[:])
- lst[0][1] = 2
- if tuple2 == tuple(lst):
- print("未改变",2)
- else:
- print("已改变",2)
复制代码
列表嵌套拷贝你会发现
虽然列表不同,但是里面的元素都是同一个ID
- lst = [[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0]]
- lst1 = lst[:]
- print(lst1 is lst)
- print(lst1[0] is lst[0])
复制代码
这时候可以给每个元素做切片
- lst = [[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0]]
- lst1 = [i[:] for i in lst]
- print(lst is lst1)
- print(lst[0] is lst1[0])
- lst[0][1] = 1
- print(lst)
- print(lst1)
复制代码
- lst = [[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0]]
- lst1 = [i[:] for i in lst]
- lst[0][1] = 1
- if lst1 == lst:
- print("未改变",1)
- else:
- print("已改变",1)
复制代码
|