【发布时间】:2021-06-17 22:47:12
【问题描述】:
我创建了一个空的二维数组。当我尝试在其中添加内容时,它无法正确执行。每个索引都包含适当的信息,但出于某种原因,会将前一个索引中的信息携带到下一个索引中。这是我的代码:
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
我在控制台中得到的结果是:
['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。
【问题讨论】:
-
这看起来不错!您还期望拥有什么?请显示您的预期输出,以便我们知道您想要做什么。
标签: python arrays for-loop multidimensional-array