简体   繁体   English

在 numpy 中获取随机洗牌前缀的最快方法

[英]Fastest way to get the prefix of a random shuffle in numpy

As an example, say we want a random 13-card hand from a 52-card deck.例如,假设我们想要从一副 52 张牌的牌组中随机抽取 13 张牌。 We can randomly shuffle all 52 cards and extract the first 13:我们可以随机洗所有 52 张牌并提取前 13 张:

    import numpy as np
    cards = np.arange(52)
    rng = np.random.default_rng()
    rng.shuffle(cards)
    hand = cards[:13]

Is there a faster way given that we only need a prefix of the shuffled result?鉴于我们只需要打乱结果的前缀,是否有更快的方法? (Including when the array sizes are larger.) (包括数组大小较大时。)

You could randomly choose from the range, without shuffling:您可以从范围中随机选择,无需洗牌:

np.random.choice(cards, size=13, replace=False)

#edit: #编辑:

however, actually timing this:然而,实际计时:

%%timeit -r 10 -n 10

rng.shuffle(cards)
hand = cards[:13]

The slowest run took 7.99 times longer than the fastest. This could mean that an intermediate result is being cached.
8.14 µs ± 8.42 µs per loop (mean ± std. dev. of 10 runs, 10 loops each)

vs:对比:

%%timeit -r 10 -n 10

np.random.choice(cards, size=13, replace=False)

22.2 µs ± 7.22 µs per loop (mean ± std. dev. of 10 runs, 10 loops each)

vs:对比:

%%timeit -r 10 -n 10

np.random.shuffle(cards)
hand = cards[:13]

3.18 µs ± 699 ns per loop (mean ± std. dev. of 10 runs, 10 loops each)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM