我想知道为什么要在我的列表中的每个列表中添加一个数字。不仅仅是我选择的那个([0])。写[0]和在append后面写其他数字有什么区别
j = [[]] * 5
j[0].append(5) # add 5 to every list on list
j[1].append(4) # what's the diffrence? [1] or [0]; it adds number to every element anyway
print (j)
j.append(0) # add 0 to the main list
print (j)
Tags:
没有区别
j = [[]] * 5
重复相同的空列表实例五次,每个索引一次
这样,初始空列表被引用了5次
您可以验证:
id(j[0]) == id(j[1])
在每个索引处实例化不同的空列表需要理解:
[[] for _ in range(5)]
这是因为您的初始列表
j
包含5个对同一对象的引用(因此5个副本到同一个列表)。这就是为什么你附加的所有东西都会出现在每个列表中相反,如果您实际创建了5个不同的子列表:
j = [[] for _ in range(5)]
然后它将按您的预期工作:
[[5], [4], [], [], [], 0]
相关问题 更多 >
编程相关推荐