13

与我的标题相同的先前问题已发布,(我认为)相同的问题,但代码中存在其他问题。我无法确定该案例是否与我的相同。

无论如何,我想替换列表中列表中的元素。代码:

myNestedList = [[0,0]]*4 # [[0, 0], [0, 0], [0, 0], [0, 0]]
myNestedList[1][1] = 5

我现在期望:

[[0, 0], [0, 5], [0, 0], [0, 0]]

但我得到:

[[0, 5], [0, 5], [0, 5], [0, 5]]

为什么?

这在命令行中被复制。linux2 上的 Python 3.1.2(r312:79147,2010 年 4 月 15 日,15:35:48)[GCC 4.4.3]

4

1 回答 1

20

您有四个 * 4 对同一对象的引用,请使用列表理解和范围进行计数:

my_nested_list = [[0,0] for count in range(4)]
my_nested_list[1][1] = 5
print(my_nested_list)

为了更具体地解释这个问题:

yourNestedList = [[0,0]]*4
yourNestedList[1][1] = 5
print('Original wrong: %s' % yourNestedList)

my_nested_list = [[0,0] for count in range(4)]
my_nested_list[1][1] = 5
print('Corrected: %s' % my_nested_list)

# your nested list is actually like this
one_list = [0,0]
your_nested_list = [ one_list for count in range(4) ]
one_list[1] = 5
print('Another way same: %s' % your_nested_list)
于 2010-10-04T11:45:15.070 回答