python - 如何获得所有可能的排列?
问题描述
我有一个嵌套列表
x = [['a', 'b', 'c'], ['d'], ['e', 'f', ['g', ['h', 'i']]]]
我想在不超出相应子列表的情况下对子列表中的元素进行所有可能的排列。预期的输出是这样的变化:
[['c', 'b', 'a'], ['d'], ['f', 'e', ['g', ['i', 'h']]]]
[['d'], ['a', 'b', 'c'], ['f', 'e', [['h', 'i'], 'g']]]
必须保留的每个元素都保存在方括号中。
我写这个生成器:
def swap(x):
if isinstance(x, list):
res = np.random.choice(x, len(x), replace = False)
return [list(map(ff, res))]
else:
return x
它给出了预期结果的随机变体,但我需要将它们全部收集起来。我怎么能做到?我应该这样做:
my_list = []
for i in range(10000): # not necessary 10000, any huge number
my_list.append(ff(yy1))
然后将 unique 函数应用于 my_list 以选择唯一的,或者还有其他选择?
解决方案
不是特别pythonic,但我会通过查找索引的排列来接近它,如下所示:
from itertools import permutations
mylist= [[1], [1,2], [1,2,3]]
combinations = list(permutations([i for i in range(len(mylist))]))
print(combinations)
for item in combinations:
print([mylist[item[i]] for i in range(len(mylist))])
Output:
[(0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0)]
[[1], [1, 2], [1, 2, 3]]
[[1], [1, 2, 3], [1, 2]]
[[1, 2], [1], [1, 2, 3]]
[[1, 2], [1, 2, 3], [1]]
[[1, 2, 3], [1], [1, 2]]
[[1, 2, 3], [1, 2], [1]]