【问题标题】:For loop doesn't append info correctly into 2D arrayFor 循环没有正确地将信息附加到二维数组中
【发布时间】: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


【解决方案1】:

问题在于:

array = [[]*cols]*rows

首先,[]*cols 只是创建 一个 空列表(空的,因为 * 运算符没有什么可重复的)。但更重要的是,*row 只是复制了对该列表的引用,但不会创建 new 空列表。因此,无论您对该 single 列表做什么,都将在外部列表的所有插槽中可见。

所以改变:

array = [[]*cols]*rows 

列表理解:

array = [[] for _ in range(rows)]

改进

不是您的问题,但您可以省略循环并使用上述列表推导立即用数据填充列表:

array = [[fruit, 0] for fruit in ['apples', 'bananas', 'oranges']]

【讨论】:

  • 另一种方法是使用 array.append([fruit_list[i],0]) 然后你可以使用 array=[] 初始化数组
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-28
  • 2021-08-10
  • 1970-01-01
  • 1970-01-01
  • 2012-11-15
  • 2021-11-24
相关资源
最近更新 更多