鱼C论坛

 找回密码
 立即注册
查看: 1457|回复: 2

[已解决]大佬们,我头都大了,列表前后比较这么费劲吗?

[复制链接]
发表于 2021-2-15 02:25:21 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
也用了切片了也用了元组了,就是没效果,求大神给支招!
捕获.PNG
  1. lst = [[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0]]

  2. lst1 = lst[:]
  3. lst[0][1] = 1

  4. if lst1 == lst:
  5.     print("未改变",1)
  6. else:
  7.     print("已改变",1)

  8. tuple2 = tuple(lst[:])
  9. lst[0][1] = 2

  10. if tuple2 == tuple(lst):
  11.     print("未改变",2)
  12. else:
  13.     print("已改变",2)
复制代码
最佳答案
2021-2-15 03:46:17
列表嵌套拷贝你会发现

虽然列表不同,但是里面的元素都是同一个ID

  1. lst = [[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0]]

  2. lst1 = lst[:]

  3. print(lst1 is lst)

  4. print(lst1[0] is lst[0])
复制代码


这时候可以给每个元素做切片

  1. lst = [[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0]]

  2. lst1 = [i[:] for i in lst]

  3. print(lst is lst1)

  4. print(lst[0] is lst1[0])

  5. lst[0][1] = 1

  6. print(lst)

  7. print(lst1)
复制代码

  1. lst = [[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0]]

  2. lst1 = [i[:] for i in lst]
  3. lst[0][1] = 1

  4. if lst1 == lst:
  5.     print("未改变",1)
  6. else:
  7.     print("已改变",1)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2021-2-15 03:46:17 | 显示全部楼层    本楼为最佳答案   
列表嵌套拷贝你会发现

虽然列表不同,但是里面的元素都是同一个ID

  1. lst = [[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0]]

  2. lst1 = lst[:]

  3. print(lst1 is lst)

  4. print(lst1[0] is lst[0])
复制代码


这时候可以给每个元素做切片

  1. lst = [[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0]]

  2. lst1 = [i[:] for i in lst]

  3. print(lst is lst1)

  4. print(lst[0] is lst1[0])

  5. lst[0][1] = 1

  6. print(lst)

  7. print(lst1)
复制代码

  1. lst = [[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0]]

  2. lst1 = [i[:] for i in lst]
  3. lst[0][1] = 1

  4. if lst1 == lst:
  5.     print("未改变",1)
  6. else:
  7.     print("已改变",1)
复制代码

评分

参与人数 1鱼币 +2 收起 理由
qq1151985918 + 2 无条件支持楼主!

查看全部评分

小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

 楼主| 发表于 2021-2-15 05:25:55 | 显示全部楼层
逃兵 发表于 2021-2-15 03:46
列表嵌套拷贝你会发现

虽然列表不同,但是里面的元素都是同一个ID

感谢感谢!
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-27 21:18

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表