这里有一种更加健壮/通用的方法来完成你想要的事情。我先定义一个辅助函数:
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]),
subsets_of_length(['BB','BC'], [1,2]),
subsets_of_length(['CD','CF','CG'], [0,1,2,3]),
)):
print(' '.join(column for column in choices if column))