2015-11-26 66 views
-2

我想改变一个嵌套列表中的一个单元格,并获取所有嵌套列表中的单元格。python嵌套列表中的一个bug

例如:

>>> temp_list = [['a']*2]*3 
>>> temp_list 
[['a', 'a'], ['a', 'a'], ['a', 'a']] 
>>> temp_list[2][0] = 'b' 
>>> temp_list 
[['b', 'a'], ['b', 'a'], ['b', 'a']] 
>>> 

在此先感谢!

+0

这是因为[ '一'] [地址的 'A',地址 '一']而不是[数据 'A',数据“一的* 2]制作列表“]。当你做了分配时,那个地址的值被更新而不是数据。 –

+0

这不是一个错误。列表是一个可变的序列类型。 检查此网址:https://docs.python.org/2/library/functions.html#list –

+0

另一个有趣的链接,了解正在发生的事情:https://en.wikibooks.org/wiki/Python_Programming/列表#List_creation_shortcuts – Antwane

回答

2

我知道,这听起来很错误的,但...

这是不是一个错误,这是一个特点。

>>> [id(x) for x in temp_list] 
[4473545216, 4473545216, 4473545216] 

正如你可以看到,他们都有着相同的参考。因此,您需要创建列表的副本。

0

2.7中我得到了相同的行为。来自*扩展的每个实例引用相同的变量。

>>> temp_list = [['a']*2]*3 
>>> temp_list 
[['a', 'a'], ['a', 'a'], ['a', 'a']] 
>>> temp_list[2][0] = 'b' 
>>> temp_list 
[['b', 'a'], ['b', 'a'], ['b', 'a']] 
>>> temp_list[1][0] = 'c' 
>>> temp_list 
[['c', 'a'], ['c', 'a'], ['c', 'a']] 
>>> temp_list[1][1] = 'x' 
>>> temp_list 
[['c', 'x'], ['c', 'x'], ['c', 'x']] 

参见:Python initializing a list of lists