numpy中的非重复随机数 [英] Non-repetitive random number in numpy

查看:585
本文介绍了numpy中的非重复随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在numpy中生成非重复的随机数?

How can I generate non-repetitive random numbers in numpy?

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

推荐答案

numpy.random.Generator.choice offers a replace argument to sample without replacement:

from numpy.random import default_rng

rng = default_rng()
numbers = rng.choice(20, size=10, replace=False)

如果您使用的是1.17之前的NumPy,而没有Generator API,则可以使用

If you're on a pre-1.17 NumPy, without the Generator API, you can use random.sample() from the standard library:

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

您还可以使用numpy.random.shuffle()和切片,但这会降低效率:

You can also use numpy.random.shuffle() and slicing, but this will be less efficient:

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

在旧版numpy.random.choice函数中也有一个replace自变量,但是由于随机数流稳定性的保证,该自变量的实现效率很低,然后变得效率低下,因此不建议使用它. (基本上是在内部执行随机播放和切片操作.)

There's also a replace argument in the legacy numpy.random.choice function, but this argument was implemented inefficiently and then left inefficient due to random number stream stability guarantees, so its use isn't recommended. (It basically does the shuffle-and-slice thing internally.)

这篇关于numpy中的非重复随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆