python - 自动填充 python 列表列表

标签 python list

<分区>

当我创建并填充列表列表时,会弹出一些奇怪的行为:

list1 = [[0,0,0],[0,0,0],[0,0,0]]
list2 = [[0]*3]*3

print('lists still look equal here:')
print(list1)
print(list2)

list1[1].pop(1)
list2[1].pop(1)

print('but not anymore:')
print(list1)
print(list2)

给我这个输出:

lists look completely equal here:
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
but not anymore:
[[0, 0, 0], [0, 0], [0, 0, 0]]
[[0, 0], [0, 0], [0, 0]]

所以第二个列表从每个小列表中“弹出”,而不仅仅是我正在尝试的那个。我想知道是什么导致了这种行为,如果我需要大量的长列表而不仅仅是这些小列表,是否有更优雅的方法来填充可索引列表?

最佳答案

当使用运算符 * 时,这意味着项目指向相同的内存位置。

因此,当从第一个列表弹出时,只有第一个项目被删除。

当从第二个列表中弹出时,由于列表中的每个元素都指向相同的内存位置,所有元素都会受到影响。

看看这个:

list1 = [[0,0,0],[0,0,0],[0,0,0]]
list2 = [[0]*3]*3

for elem in list1:
    print (id(elem))

print ('--------')
for elem in list2:
    print (id(elem))

输出:

32969912
32937024
32970192
--------
32970752
32970752
32970752

如您所见,第二个列表中的每个元素都具有相同的 id。

关于python - 自动填充 python 列表列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46264223/

相关文章:

c# - 搜索 List<List<string>> 的最佳方法是什么?

python - 如何将多列分组以在 pandas DataFrame 中列出

python - Pandas groupby 聚合截断最早日期而不是最旧日期

python - Tensorflow无法训练模型

python - Pandas Series float 索引

python - 如何按 JSON 的值进行复制?

c# - 了解 LINQ 子查询

python - 使用 Python Flask 在我的 html 中显示 .txt 文件

python - 无法导入ndb

javascript - 如何挂接到浏览器的上下文菜单事件