python如何更改嵌套列表中的元素 [英] python how to change element in nested list
问题描述
我已经使用python很多次了,今天我对一个简单的嵌套列表感到惊讶.
I have been using python for a lot and today I get surprised by a simple nested list.
如何更改列表元素的值?
How can I change the value of an element of my list?
>>> l=[[0,0]]*10
>>> l
[[0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0]]
>>> l[0]
[0, 0]
>>> l[0][0]
0
>>> l[0][0]=1 #here comes the question
>>> l
[[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]
>>>
我希望最终结果
l=[[1,0],[0,0],[0,0]...]
为什么不附加? (我想要一个理论上的解释) 如何获得理想的结果?
Why it does not append? (I would like a theoretical explanation ) How can I get the desired result?
谢谢.
以另一种方式启动列表时,我得到了预期的结果
In starting the list in another way I get the desired result
>> l=[[0,0],[0,0]]
>>> l
[[0, 0], [0, 0]]
>>> l[0][0]=1
>>> l
[[1, 0], [0, 0]]
>>>
但是我仍然想知道为什么第一个版本不起作用以及如何初始化很多元素的列表?
but I am still wondering why the first version does not work and how can I initialize a list of a lot of elements?
推荐答案
您有10次相同 [0, 0]
元素的列表:
You have a list of the same [0, 0]
element 10 times here:
l=[[0,0]]*10
每次修改一个,它都会全部修改,因为它们是相同的列表.
Any time you modify one, it modifies them all, because they're the same list.
使它们与众不同的一种安全方法是:
One safe way to make them unique would be:
l = [[0, 0] for _ in range(10)]
一种简单的检查方法是打印每个的id
,这是存储它的内存地址:
One easy way to check would be to print the id
of each, which is the memory address where it's stored:
>>> for element in l:
... print id(element)
...
34669128
34669128
34669128
34669128
34669128
34669128
34669128
34669128
34669128
34669128
这篇关于python如何更改嵌套列表中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!