本文介绍了在Python中使用循环定义列表清单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用Python循环定义列表列表.我要构建以下列表:
I am trying to define a list of lists with a loop in Python. I want to construct the following list:
x=[[0,0],[1,0],[2,0],...,[9,0]]
这基本上是我要做的:
x=[[0,0]]*10
for i in range(10):
x[i][0]=i
print x
但是,我最终得到以下列表:
However, I end up with the following list:
x=[[9,0],[9,0],[9,0],...,[9,0]]
我做错了什么?非常感谢您的帮助
What am I doing wrong? Thank you so much for your help
推荐答案
您要这样做吗?
>>> [[i, 0] for i in range(10)]
[[0, 0], [1, 0], [2, 0], [3, 0], [4, 0], [5, 0], [6, 0], [7, 0], [8, 0], [9, 0]]
您这样做的问题是创建了一个列表,然后使用*
并没有创建更多列表,而是只是对其进行了更多引用,这意味着每次更改列表时,列表中,您每次都更改相同列表.
What was wrong with that you were doing is that you were creating a list, and then by using the *
you were not creating more, you were just making more references to it, this means that each time you changed the list, you were changing the same list each time.
>>> a = [[]]*10
>>> a
[[], [], [], [], [], [], [], [], [], []]
>>> a[0].append('X')
>>> a
[['X'], ['X'], ['X'], ['X'], ['X'], ['X'], ['X'], ['X'], ['X'], ['X']]
这篇关于在Python中使用循环定义列表清单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!