Warm tip: This article is reproduced from serverfault.com, please click

Fill a 2D list with random numbers in python

发布于 2020-11-28 16:34:19

I have created a function to fill a 2D array, but it does not work as intended:

from random import *

def fill_matrix(maxrow, maxcol):
    mymatrix = [ [ None ] * maxrow ] * maxcol
    for row_index in range(0, len(mymatrix)):
        for col_index in range(0, len(mymatrix[row_index])):
            mymatrix[row_index][col_index] = randint(0, 9)
            print(row_index, col_index, ": ", mymatrix)
    print(mymatrix)
                               
fill_matrix(3, 4)

But it always fills every column with the same number, although I specified [row_index][col_index]:

Result output:

0 0 :  [[0, None, None], [0, None, None], [0, None, None], [0, None, None]]
0 1 :  [[0, 2, None], [0, 2, None], [0, 2, None], [0, 2, None]]
0 2 :  [[0, 2, 0], [0, 2, 0], [0, 2, 0], [0, 2, 0]]
1 0 :  [[4, 2, 0], [4, 2, 0], [4, 2, 0], [4, 2, 0]]
1 1 :  [[4, 1, 0], [4, 1, 0], [4, 1, 0], [4, 1, 0]]
1 2 :  [[4, 1, 6], [4, 1, 6], [4, 1, 6], [4, 1, 6]]
2 0 :  [[0, 1, 6], [0, 1, 6], [0, 1, 6], [0, 1, 6]]
2 1 :  [[0, 2, 6], [0, 2, 6], [0, 2, 6], [0, 2, 6]]
2 2 :  [[0, 2, 3], [0, 2, 3], [0, 2, 3], [0, 2, 3]]
3 0 :  [[8, 2, 3], [8, 2, 3], [8, 2, 3], [8, 2, 3]]
3 1 :  [[8, 7, 3], [8, 7, 3], [8, 7, 3], [8, 7, 3]]
3 2 :  [[8, 7, 3], [8, 7, 3], [8, 7, 3], [8, 7, 3]]
[[8, 7, 3], [8, 7, 3], [8, 7, 3], [8, 7, 3]]
Questioner
Raf van de Vreugde
Viewed
0
venky__ 2020-11-29 02:39:07

when you do arr= [[None]*2]*3 you create a list with 3 lists referencing to same list. so if one list changes all the other ones will change. So replace mymatrix = [ [ None ] * maxrow ] * maxcol by

mymatrix = [ [ None for i in range (maxrow) ] for j in range (maxcol)]