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)
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))
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]
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.)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…