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

arrays-用python中的随机数填充2D列表

(arrays - Fill a 2D list with random numbers in python)

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

我创建了一个函数来填充2D数组,但是它无法按预期工作:

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)

尽管我指定了[row_index] [col_index],但它总是用相同的数字填充每一列:

结果输出:

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
11
venky__ 2020-11-29 02:39:07

当你arr= [[None]*2]*3创建一个包含3个引用同一列表的列表的列表时。因此,如果一个列表更改,其他所有列表都会更改。所以替换mymatrix = [ [ None ] * maxrow ] * maxcol

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