您应该使用itertools库.您想要生成powerset中每个元素的所有唯一排列.有些代码可能看起来像
from itertools import permutations, combinations, chain
# Taken from itertools page, but edited slightly to not return empty set
def powerset(iterable):
"powerset([1,2,3]) --> (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(1, len(s)+1))
然后
In [1]: s = ('A', 'B', 'C')
In [2]: [j for i in powerset(s) for j in permutations(i)]
Out[2]:
[('A',),
('B',),
('C',),
('A', 'B'),
('B', 'A'),
('A', 'C'),
('C', 'A'),
('B', 'C'),
('C', 'B'),
('A', 'B', 'C'),
('A', 'C', 'B'),
('B', 'A', 'C'),
('B', 'C', 'A'),
('C', 'A', 'B'),
('C', 'B', 'A')]