Non-repetitive random number in numpy

∥☆過路亽.° 提交于 2019-11-27 12:00:50

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]
strnam

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)

You can get this by sorting as well:

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

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.

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