且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

python,从(1,n)中选择随机#k个数字,不包括列表中的数字

更新时间:2023-02-09 21:20:24

sample 的文档字符串:

Sample notes in sample's docstring:

要在整数范围内选择样本,请使用 range 作为参数.这对于从一个大人口:样本(范围(10000000),60)

To choose a sample in a range of integers, use range as an argument. This is especially fast and space efficient for sampling from a large population: sample(range(10000000), 60)

我可以在我的机器上测试这个:

I can test this on my machine:

In [11]: sample(range(100000000), 3)
Out[11]: [70147105, 27647494, 41615897]

In [12]: list(range(100000000))  # crash/takes a long time

有效地使用排除列表进行采样的一种方法是使用相同的范围技巧,但跳过"排除项(我们可以在 O(k * log(len(exclude_list)) 中执行此操作)) 与 bisect 模块:


One way to sample with an exclude list efficiently is to use the same range trick but "hop over" the exclusions (we can do this in O(k * log(len(exclude_list))) with the bisect module:

import bisect
import random

def sample_excluding(n, k, excluding):
    # if we assume excluding is unique and sorted we can avoid the set usage...
    skips = [j - i for i, j in enumerate(sorted(set(excluding)))]
    s = random.sample(range(n - len(skips)), k)
    return [i + bisect.bisect_right(skips, i) for i in s]

我们可以看到它在工作:

and we can see it working:

In [21]: sample_excluding(10, 3, [2, 4, 7])
Out[21]: [6, 3, 9]

In [22]: sample_excluding(10, 3, [1, 2, 8])
Out[22]: [0, 4, 3]

In [23]: sample_excluding(10, 6, [1, 2, 8])
Out[23]: [0, 7, 9, 6, 3, 5]

特别是我们在不使用 O(n) 内存的情况下做到了这一点:

Specifically we've done this without using O(n) memory:

In [24]: sample_excluding(10000000, 6, [1, 2, 8])
Out[24]: [1495143, 270716, 9490477, 2570599, 8450517, 8283229]