[英]Making all possible combination of lists in lists
我已經找到了解決這個問題的幾種方法,但這不是我打算做的。
當我有清單時:
[1,2,3],[4,5,6],[7,8,9]
我想擁有所有可能的組合:
[1,2,3],[7,8,9],[4,5,6]
[1,2,3],[4,5,6],[7,8,9]
[7,8,9],[4,5,6],[1,2,3]
....
但是在python中有一個簡單的解決方案嗎?
謝謝,也可以創建1個列表而不是3個列表,例如:[7,8,9,4,5,6,1,2,3]
我認為itertools.permutations
是您要尋找的。
>>> import itertools
>>> l = [1,2,3],[4,5,6],[7,8,9]
>>> list(itertools.permutations(l, len(l)))
[([1, 2, 3], [4, 5, 6], [7, 8, 9]),
([1, 2, 3], [7, 8, 9], [4, 5, 6]),
([4, 5, 6], [1, 2, 3], [7, 8, 9]),
([4, 5, 6], [7, 8, 9], [1, 2, 3]),
([7, 8, 9], [1, 2, 3], [4, 5, 6]),
([7, 8, 9], [4, 5, 6], [1, 2, 3])]
並合並在一起:
>>> [list(itertools.chain(*x)) for x in itertools.permutations(l, len(l))]
[[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 7, 8, 9, 4, 5, 6],
[4, 5, 6, 1, 2, 3, 7, 8, 9],
[4, 5, 6, 7, 8, 9, 1, 2, 3],
[7, 8, 9, 1, 2, 3, 4, 5, 6],
[7, 8, 9, 4, 5, 6, 1, 2, 3]]
>>> from itertools import permutations
>>> a = [[1,2,3],[4,5,6],[7,8,9]]
>>> for permu in permutations(a,3):
... print permu
...
([1, 2, 3], [4, 5, 6], [7, 8, 9])
([1, 2, 3], [7, 8, 9], [4, 5, 6])
([4, 5, 6], [1, 2, 3], [7, 8, 9])
([4, 5, 6], [7, 8, 9], [1, 2, 3])
([7, 8, 9], [1, 2, 3], [4, 5, 6])
([7, 8, 9], [4, 5, 6], [1, 2, 3])
使用reduce
組合列表:
>>> a = [[1,2,3],[4,5,6],[7,8,9]]
>>> for permu in permutations(a,3):
... print reduce(lambda x,y: x+y,permu,[])
...
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 7, 8, 9, 4, 5, 6]
[4, 5, 6, 1, 2, 3, 7, 8, 9]
[4, 5, 6, 7, 8, 9, 1, 2, 3]
[7, 8, 9, 1, 2, 3, 4, 5, 6]
[7, 8, 9, 4, 5, 6, 1, 2, 3]
在Python2.7中,您無需指定排列的長度
>>> T=[1,2,3],[4,5,6],[7,8,9]
>>> from itertools import permutations
>>> list(permutations(T))
[([1, 2, 3], [4, 5, 6], [7, 8, 9]), ([1, 2, 3], [7, 8, 9], [4, 5, 6]), ([4, 5, 6], [1, 2, 3], [7, 8, 9]), ([4, 5, 6], [7, 8, 9], [1, 2, 3]), ([7, 8, 9], [1, 2, 3], [4, 5, 6]), ([7, 8, 9], [4, 5, 6], [1, 2, 3])]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.