问题描述
我创建了一个空的2D数组.当我尝试在其中添加内容时,这样做不正确.每个索引都包含适当的信息,但是由于某种原因,会将信息从上一个索引携带到下一个索引.这是我的代码:
I have created an empty 2D array. When I try to add stuff inside of it, it doesn't do so properly. Each index contains the appropriate info, but for some reason, carries the info from the previous into the next index. Here is my code:
rows, cols = (3, 2)
array = [[]*cols]*rows # Creating the empty 2D array.
fruit_list = ['apples', 'bananas', 'oranges'] # My fruit list
for i in range(0, 3):
array[i].append(fruit_list[i]) # Appending to the 2D array a fruit,
array[i].append(0) # followed by the number 0
print(array[i]) # Printing each index
我在控制台中得到的结果是:
The result I am getting in the console is :
['apples', 0] # This is good (index 1)
['apples', 0, 'bananas', 0] # This is not good (index 2)
['apples', 0, 'bananas', 0, 'oranges', 0] # This is not good (index 3)
# etc.
如何阻止这种情况的发生?我希望每个索引都有自己的果实和数字0.
How do I stop this from happening? I want each index to have its own fruit and number 0.
推荐答案
问题出在这里:
array = [[]*cols]*rows
首先, [] * cols
只是创建一个一个空列表(为空,因为 *
运算符无需重复).但更重要的是, * row
只是复制对该列表的引用,而不会创建 new 空列表.因此,无论您对那个单个列表执行什么操作,都将在外部列表的所有插槽中看到.
First, []*cols
is just creating one empty list (empty, because the *
operator has nothing to repeat). But more importantly, *row
just duplicates the reference to that list, but does not create new empty lists. So whatever you do to that single list, will be visible in all the slots of the outer list.
所以改变:
array = [[]*cols]*rows
对列表的理解:
array = [[] for _ in range(rows)]
改进
不是您的问题,但是您可以省略循环,并使用上述列表理解功能立即用数据填充列表:
Improvement
Not your question, but you can omit the loop and use the above mentioned list comprehension to immediately populate the list with the data:
array = [[fruit, 0] for fruit in ['apples', 'bananas', 'oranges']]
这篇关于For循环无法将信息正确附加到2D数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!