Non-repetitive random number in numpy

别等时光非礼了梦想. 提交于 2019-11-26 15:51:44

问题


My question is: How can I generate non-repetitive random numbers in numpy?

list = np.random.random_integers(20,size=(10))

回答1:


If you don't insist on using NumPy, you can use random.sample() from the standard library:

print random.sample(range(20), 10)

With NumPy, you will have to use numpy.random.shuffle() and slicing:

a = numpy.arange(20)
numpy.random.shuffle(a)
print a[:10]



回答2:


I think numpy.random.sample doesn't work right, now. This is my way:

import numpy as np
np.random.choice(range(20), 10, replace=False)



回答3:


You can get this by sorting as well:

random_numbers = np.random.random([num_samples, max_int])
samples = np.argsort(random_numbers, axis=1)



回答4:


Simply generate an array that contains the required range of numbers, then shuffle them by repeatedly swapping a random one with the 0th element in the array. This produces a random sequence that doesn't contain duplicate values.



来源:https://stackoverflow.com/questions/8505651/non-repetitive-random-number-in-numpy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!