小编bli*_*liu的帖子

在Python中随机选择所有组合的子集

itertools.list(product([0, 1], repeat=n))当n很小时,我可以构造一个n长度二进制值组合的列表.

1000
0100
0110
1001
 .
 .
 .
Run Code Online (Sandbox Code Playgroud)

当n很大时,如何在不首先构建大量组合列表的情况下随机选择上面列表的子集?

假设我想在n = 30时随机选择100万个组合而不进行替换(总共2 ^ 30个组合)

我查看了itertools的扩展函数http://docs.python.org/2/library/itertools.html#recipes

def random_product(*args, **kwds):
    "Random selection from itertools.product(*args, **kwds)"
    pools = map(tuple, args) * kwds.get('repeat', 1)
    return tuple(random.choice(pool) for pool in pools)
Run Code Online (Sandbox Code Playgroud)

但它一次只返回一次.在获得100万个独特组合之前,我应该循环使用此功能吗?或者有更好的方法.谢谢!

python random combinations python-itertools

4
推荐指数
1
解决办法
499
查看次数

标签 统计

combinations ×1

python ×1

python-itertools ×1

random ×1