Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

python - For loop doesn't append info correctly into 2D array

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.

How do I stop this from happening? I want each index to have its own fruit and number 0.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The issue is with this:

array = [[]*cols]*rows

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.

So change:

array = [[]*cols]*rows 

To a list comprehension:

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']]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...