python - 从组合中随机选择

标签 python

我可以使用 list(itertools.combinations(range(n), m)) 列出所有组合,但这通常会非常大。

Given n and m, how can I choose a combination uniformly at random without first constructing a massive list??

最佳答案

itertools模块有一个从 iterable 返回随机组合的方法。下面是代码的两个版本,一个用于 Python 2.x,一个用于 Python 3.x - 在这两种情况下,您都使用 generator这意味着您不会在内存中创建一个大的可迭代对象。

假定 Python 2.x

def random_combination(iterable, r):
    "Random selection from itertools.combinations(iterable, r)"
    pool = tuple(iterable)
    n = len(pool)
    indices = sorted(random.sample(xrange(n), r))
    return tuple(pool[i] for i in indices)

在您的情况下,这样做很简单:

>>> import random
>>> def random_combination(iterable, r):
    "Random selection from itertools.combinations(iterable, r)"
    pool = tuple(iterable)
    n = len(pool)
    indices = sorted(random.sample(xrange(n), r))
    return tuple(pool[i] for i in indices)
>>> n = 10
>>> m = 3
>>> print(random_combination(range(n), m))
(3, 5, 9) # Returns a random tuple with length 3 from the iterable range(10)

以 Python 3.x 为例

在 Python 3.x 的情况下,您将 xrange 调用替换为 range,但用例仍然相同。

def random_combination(iterable, r):
    "Random selection from itertools.combinations(iterable, r)"
    pool = tuple(iterable)
    n = len(pool)
    indices = sorted(random.sample(range(n), r))
    return tuple(pool[i] for i in indices)

关于python - 从组合中随机选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22229796/

相关文章:

python - 从python中的另一个函数结束函数中的循环

Python paramiko sudo 不起作用

python - 仅根据分组记录计算 pandas 数据框中的新列

python - 使用 slider 时如何更新直方图?

python - 组合和的记忆化与非记忆化时间复杂度分析

python - 我是否需要遍历每一行数据来计算每个列类别的时间?

python - 发送自定义密码重置表格

python - 考虑到去年的第一天,今年的第一周

python - 了解字典的深度

python - 在 Mac 上从 Python 启动 Excel 文件