简体   繁体   English

用 python 中的随机数填充二维列表

[英]Fill a 2D list with random numbers in python

I have created a function to fill a 2D array, but it does not work as intended:我创建了一个 function 来填充二维数组,但它没有按预期工作:

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]:但它总是用相同的数字填充每一列,尽管我指定了 [row_index][col_index]:

Result output:结果 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]]

when you do arr= [[None]*2]*3 you create a list with 3 lists referencing to same list.当您执行arr= [[None]*2]*3时,您将创建一个包含 3 个引用同一列表的列表的列表。 so if one list changes all the other ones will change.因此,如果一个列表发生变化,所有其他列表都会发生变化。 So replace mymatrix = [ [ None ] * maxrow ] * maxcol by所以将mymatrix = [ [ None ] * maxrow ] * maxcol

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

you can try it你可以试试

import numpy as np
list2D = (np.random.random((N,N))).tolist()

output, when N=5: output,当 N=5 时:

[[0.5443335192306711, 0.06610164916627725, 0.9464264551530688, 
0.8714989296172226, 0.343053651834623], [0.4694855513495554, 
0.9109844708363358, 0.9857587537047011, 0.7607561949627727, 
0.46307440609410333], [0.050891396239376996, 0.13672955575820833, 
0.8549886951728779, 0.8803310239366302, 0.04983877880553622], 
[0.3503177755755804, 0.08222507697906556, 0.7144017087408304, 
0.6117493050623465, 0.68059136839199], [0.2244599257314427, 
0.06203059400599176, 0.9342379337438128, 0.5204524652150645, 0.44055560620795253]]

see this link: enter link description here查看此链接: 在此处输入链接描述

Try using numpy :尝试使用numpy

import numpy as np

print(np.random.randint(0,9,size=(4,3)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM