这是一种更强大/更通用的方式来执行您想要的事情.我首先定义一个辅助函数:
from itertools import combinations, chain, product
def subsets_of_length(s, lengths):
return chain.from_iterable(combinations(s,l) for l in lengths)
它产生以下输出:
>>>> list(subsets_of_length(['a','b','c'], range(2,4)))
[('a', 'b'), ('a', 'c'), ('b', 'c'), ('a', 'b', 'c')]
>>>> list(subsets_of_length(['d','e'], range(0,2)))
[(), ('d',), ('e',)]
现在我们要组合两个或多个子集,如下所示
>>>> for choices in product(
subsets_of_length(['a','b','c'], range(2,4)),
subsets_of_length(['d','e'], range(0,2)),
):
print(' '.join(str(subset) for subset in choices))
('a', 'b') ()
('a', 'b') ('d',)
('a', 'b') ('e',)
('a', 'c') ()
('a', 'c') ('d',)
('a', 'c') ('e',)
('b', 'c') ()
('b', 'c') ('d',)
('b', 'c') ('e',)
('a', 'b', 'c') ()
('a', 'b', 'c') ('d',)
('a', 'b', 'c') ('e',)
但是我们希望将这些元组链接在一起.因此,我们应该做
>>>> for choices in map(chain.from_iterable,product(
subsets_of_length(['a','b','c'], range(2,4)),
subsets_of_length(['d','e'], range(0,2)),
)):
print(' '.join(column for column in choices if column))
a b
a b d
a b e
a c
a c d
a c e
b c
b c d
b c e
a b c
a b c d
a b c e
您所编辑问题的代码为:
for choices in map(chain.from_iterable,product(
subsets_of_length(['AA','AS','AD'], [1]), #only one of these
subsets_of_length(['BB','BC'], [1,2]), #at least one of these
subsets_of_length(['CD','CF','CG'], [0,1,2,3]), #All, 1, 2 or none of these
)):
print(' '.join(column for column in choices if column))