我有一段代碼:添加條件上生成numpy的
V = numpy.floor(3*np.random.rand(5,5))
print V
它創建在5x5的表陣列的隨機結果,如何添加條件「1」僅生成的x倍,「2」僅生成y倍的,否則是「0」。 感謝
我有一段代碼:添加條件上生成numpy的
V = numpy.floor(3*np.random.rand(5,5))
print V
它創建在5x5的表陣列的隨機結果,如何添加條件「1」僅生成的x倍,「2」僅生成y倍的,否則是「0」。 感謝
試試這個:
import numpy as np
def newArray(x, y, n):
if x + y > n ** 2:
print "Values error!"
return
res = [[0 for col in range(n)] for row in range(n)]
# Create roulette
roulette = range(0, n ** 2)
printkxtimes(res, roulette, 1, x, n)
printkxtimes(res, roulette, 2, y, n)
print res
# This function draws random element from roulette,
# gets the position in array and sets value of this position to k.
# Then removes this element from roulette to prevent drawing it again
def printkxtimes(array, roulette, k, x, n):
for i in xrange(0, x):
r = int(np.floor(roulette.__len__()*np.random.rand(1))[0])
array[roulette[r]/n][roulette[r] % n] = k
roulette.pop(r)
newArray(10,2,5)
的roulette
一點解釋:
表res
的每一個元素都可以等同與一些來自range(0, n^2)
表示:
z = row*n + column <=> row = int(z/n) , column= z%n
我們可以代表李如表res
中的位置[0,1,...,n^2-1]
以下情況如何?
import numpy as np
shape = (5, 5)
area = shape[0] * shape[1]
np.random.permutation([1]*x + [2]*y + [0]*(area-x-y)).reshape(shape)
看起來很簡單。你隨機排列[1, ... 1, 2, ... 2, 0, ... 0]
然後你把它變成一個正方形。我不太確定,但它似乎也不太昂貴,並且可以很容易地擴展到數字或維度。
工作就像一個魅力......謝謝...順便說一句,如果你不介意,你可以解釋它的每一部分。 –
@RududoPain我已經添加了一些評論和解釋。 –