在python的2-D列表中更改特定元素 [英] Changing a particular element in a 2-D list in python
本文介绍了在python的2-D列表中更改特定元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码:
a=[[0]*2]*3
print a
a[1][1]=2
print a
输出为:
[[0,0],[0,0],[0,0]]
[[0,2],[0,2],[0,2]]
为什么要更改列表的所有元素?
Why is it changing all the elements of the list?
输出不应为:
[[0,0],[0,2],[0,0]]
如果我只想更改元素之一,该怎么办?
What needs to be done if I just want to change one of the element?
感谢您的帮助!
推荐答案
当您执行[0] * 2
时,这将导致列表[0, 0]
.当您将其乘以3时,您将创建一个列表,其中包含对该列表的三个引用.您可能想改为执行此操作:
When you do [0] * 2
, this results in the list [0, 0]
. When you multiply that by 3, you're creating a list with three references to that list. You probably want to do this instead:
a = [[0] * 2 for _ in range(3)]
这篇关于在python的2-D列表中更改特定元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文