python如何修改列表中的元素_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]]

>>>

I would expect as final result

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?

Thanks.

EDIT:

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?

解决方案

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值