我正在创建一个10x5的numpy零数组,我希望用1-10的数字填充每列。但是我有一个问题因为它只填充第一列而list.pop()不起作用加上我认为我的嵌套for循环,即使我尝试使用不同顺序的行和首选项。任何帮助将不胜感激。
i = 0
j = 0
for column in matrix:
preferences = [1,2,3,4,5,6,7,8,9,10]
random.shuffle(preferences)
for number in preferences:
for row in matrix:
chosen = preferences.pop(0)
matrix[j,i] = chosen
j+= 1
i+= 1
答案 0 :(得分:6)
由于您在示例中使用了pop,我认为您可能不希望在每列中重复。 numpy.random.shuffle将元素混乱到位。
>>> M = N.repeat(N.arange(1,11), 5).reshape(10,-1)
>>> M
array([[ 1, 1, 1, 1, 1],
[ 2, 2, 2, 2, 2],
[ 3, 3, 3, 3, 3],
[ 4, 4, 4, 4, 4],
[ 5, 5, 5, 5, 5],
[ 6, 6, 6, 6, 6],
[ 7, 7, 7, 7, 7],
[ 8, 8, 8, 8, 8],
[ 9, 9, 9, 9, 9],
[10, 10, 10, 10, 10]])
>>> for i in range(5):
... N.random.shuffle(M[:,i])
>>> M
array([[ 3, 9, 7, 9, 2],
[ 5, 4, 2, 5, 3],
[ 8, 8, 8, 1, 4],
[ 1, 2, 6, 10, 8],
[ 2, 1, 9, 2, 5],
[ 7, 7, 10, 7, 1],
[ 4, 3, 5, 8, 9],
[ 6, 5, 4, 4, 7],
[10, 10, 3, 6, 6],
[ 9, 6, 1, 3, 10]])
>>>
答案 1 :(得分:1)
>>> import numpy as NP
>>> fnx = lambda v : NP.random.randint(1, 11, v)
>>> A = NP.zeros(5, 10)
>>> for c in range(A.shape[0]):
A[c,:] = fnx(10)
>>> A = A.T
>>> A
array([[ 5., 1., 3., 8., 5.],
[ 4., 10., 4., 3., 10.],
[ 6., 6., 3., 2., 7.],
[ 4., 4., 10., 5., 4.],
[ 8., 6., 6., 2., 10.],
[ 10., 9., 10., 6., 10.],
[ 7., 4., 2., 2., 7.],
[ 9., 2., 9., 4., 7.],
[ 10., 5., 3., 5., 7.],
[ 3., 9., 3., 3., 1.]])