list = []
for row in range (0,5):
for col in range(0,5):
list.append(randint(0,1))
当我这样做时,我得到一个很长的数字列表。如何将其分为五个列表,每个列表包含五个元素?
答案 0 :(得分:1)
你想要一个矩阵 - 所以将数字附加到一行,当行准备就绪时,将它添加到矩阵中:
matrix = []
for row in range (0,5):
row = []
for col in range(0,5):
row.append(randint(0,1))
matrix.append(row)
答案 1 :(得分:0)
您可以使用列表理解
from random import randint
[[randint(0,1) for _ in range(5)] for _ in range(5)]
或者如果您使用NumPy
from numpy.random import randint
randint(0,2,size(5,5)).tolist()