Non-repetitive random number in numpy

2019-01-13 17:13发布

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

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

4条回答
手持菜刀,她持情操
2楼-- · 2019-01-13 17:48

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楼-- · 2019-01-13 17: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]
查看更多
beautiful°
4楼-- · 2019-01-13 17:56

You can get this by sorting as well:

random_numbers = np.random.random([num_samples, max_int])
samples = np.argsort(random_numbers, axis=1)
查看更多
男人必须洒脱
5楼-- · 2019-01-13 18:10

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.

查看更多
登录 后发表回答