Python:替换列表中的元素 (#2)

16 投票
1 回答
9725 浏览
提问于 2025-04-16 04:58

之前有一个和我问题标题一样的帖子,我觉得是同样的问题,不过那个代码有其他问题。我没法确定那种情况和我的是不是一样。

总之,我想在一个列表中的列表里替换一个元素。

代码如下:

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]]

这是为什么呢?

这个问题在命令行中也能重现。

我用的是Python 3.1.2(r312:79147,2010年4月15日,15:35:48)

[GCC 4.4.3] 在linux2上运行

1 个回答

22

你有四个地方都指向同一个对象,建议用列表推导式和范围来计数:

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)

撰写回答