这是另一个想法:存储组合生成器并随机生成,直到你消耗所有。这也使集合大小的顺序随机化。
编辑:我假设您不关心单个集合中元素的顺序,因为您将对它们求和。如果你这样做了,你可以random.shuffle(next_value)
在 yield 之前放一个。
import itertools
import random
def random_powerset(l):
combs = [itertools.combinations(l,i) for i in range(len(l)+1)]
while combs:
comb_index = random.choice(range(len(combs)))
try:
next_value = next(combs[comb_index])
yield next_value
except StopIteration:
combs.pop(comb_index)
输出:
In : list(random_powerset(range(3)))
Out: [(0, 1), (0, 2), (0, 1, 2), (1, 2), (), (0,), (1,), (2,)]
In : list(random_powerset(range(3)))
Out: [(0, 1, 2), (0,), (), (0, 1), (1,), (0, 2), (1, 2), (2,)]
In : list(random_powerset(range(3)))
Out: [(0, 1), (0, 1, 2), (0, 2), (), (0,), (1,), (1, 2), (2,)]
In : list(random_powerset(range(3)))
Out: [(), (0,), (0, 1), (0, 1, 2), (1,), (0, 2), (2,), (1, 2)]
In : list(random_powerset(range(3)))
Out: [(), (0, 1), (0,), (0, 1, 2), (1,), (0, 2), (2,), (1, 2)]
In : list(random_powerset(range(3)))
Out: [(0, 1), (0,), (0, 2), (1, 2), (), (1,), (2,), (0, 1, 2)]
In : list(random_powerset(range(3)))
Out: [(), (0, 1, 2), (0,), (1,), (2,), (0, 1), (0, 2), (1, 2)]