[英]Python: Replacing an element in a list of lists (#2)
我發布了與我的標題相同的上一個問題(我認為)同樣的問題,但代碼中還有其他問題。 我無法確定該案件是否與我的相同。
無論如何,我想替換列表中列表中的元素。 碼:
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,使用list comprehension和range來計算:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.