Python 列表赋值 BUG

2022-10-19 14:51:34 +08:00
 lz24xg

s = [1,2,3,4,[5,5,5,5]] candle = {'h':9, 'l':7, 'c':6}

print(s[-2:]) s[-1][2] = candle['h'] s[-1][3] = candle['l'] print(s[-2:]) s.append(s[-1]) print(s[-2:]) s[-1][2] = candle['c'] s[-1][3] = candle['c'] print(s[-3:])

输出: [4, [5, 5, 5, 5]] [4, [5, 5, 9, 7]] [[5, 5, 9, 7], [5, 5, 9, 7]] [4, [5, 5, 6, 6], [5, 5, 6, 6]]

我改了 list 最后一个元素的值,因为后 2 个元素是相同的值,所以倒数第 2 个也被修改了?这是 Python 的 BUG 吗?

1578 次点击
所在节点    Python
9 条回复
ranleng
2022-10-19 14:54:34 +08:00
代码看的头疼,
大概率是同一个对象导致的
learningman
2022-10-19 14:54:55 +08:00
请自行复习 值与引用
lizytalk
2022-10-19 14:59:10 +08:00
s.append(s[-1])之后,s 中的后两个元素指向的是相同的 list 对象
superrichman
2022-10-19 14:59:30 +08:00
你 append 的是一个指针,s[-1]和 s[-2]都指向同一个 list 。改成 s.append(s[-1] * 1) 创建一个新的对象
huangzhe8263
2022-10-19 15:01:51 +08:00
use reference 和 use value 的问题

记得有一个可视化这个问题的网站,我去翻翻
huangzhe8263
2022-10-19 15:04:51 +08:00
huangzhe8263
2022-10-19 15:05:12 +08:00
lz24xg
2022-10-19 15:07:35 +08:00
感谢,解决了
TimePPT
2022-10-19 15:20:08 +08:00
In [1]: s = [1,2,3,4,[5,5,5,5]]

In [2]: candle = {'h':9, 'l':7, 'c':6}

In [3]: s[-1][2] = candle['h']

In [4]: s[-1][3] = candle['l']

In [5]: s.append(s[-1])

In [6]: s[-1][2] = candle['c']

In [7]: s[-1][3] = candle['c']

In [8]: for i in s:
...: print(f"{i=}, {type(i)=}, {id(i)=}")
...:
i=1, type(i)=<class 'int'>, id(i)=4549804272
i=2, type(i)=<class 'int'>, id(i)=4549804304
i=3, type(i)=<class 'int'>, id(i)=4549804336
i=4, type(i)=<class 'int'>, id(i)=4549804368
i=[5, 5, 6, 6], type(i)=<class 'list'>, id(i)=4582898496
i=[5, 5, 6, 6], type(i)=<class 'list'>, id(i)=4582898496

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/888120

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX