2016-03-18 64 views
1

當我嘗試計算如何在Python中獲取列表列表的所有排列和組合時,我的大腦將會爆炸。問題是寫這將以下輸入列表[['I1', 'I2', 'I3'], ['I2', 'I3']]返回以下功能:Python itertools獲取排列和列表列表的組合

[['I1', 'I2', 'I3'], ['I2', 'I3']] 
[['I1', 'I3', 'I2'], ['I2', 'I3']] 
[['I2', 'I1', 'I3'], ['I2', 'I3']] 
[['I2', 'I3', 'I1'], ['I2', 'I3']] 
[['I3', 'I1', 'I2'], ['I2', 'I3']] 
[['I3', 'I2', 'I1'], ['I2', 'I3']] 
[['I1', 'I2', 'I3'], ['I3', 'I2']] 
[['I1', 'I3', 'I2'], ['I3', 'I2']] 
[['I2', 'I1', 'I3'], ['I3', 'I2']] 
[['I2', 'I3', 'I1'], ['I3', 'I2']] 
[['I3', 'I1', 'I2'], ['I3', 'I2']] 
[['I3', 'I2', 'I1'], ['I3', 'I2']] 
[['I2', 'I3'], ['I1', 'I2', 'I3']] 
[['I2', 'I3'], ['I1', 'I3', 'I2']] 
[['I2', 'I3'], ['I2', 'I1', 'I3']] 
[['I2', 'I3'], ['I2', 'I3', 'I1']] 
[['I2', 'I3'], ['I3', 'I1', 'I2']] 
[['I2', 'I3'], ['I3', 'I2', 'I1']] 
[['I3', 'I2'], ['I1', 'I2', 'I3']] 
[['I3', 'I2'], ['I1', 'I3', 'I2']] 
[['I3', 'I2'], ['I2', 'I1', 'I3']] 
[['I3', 'I2'], ['I2', 'I3', 'I1']] 
[['I3', 'I2'], ['I3', 'I1', 'I2']] 
[['I3', 'I2'], ['I3', 'I2', 'I1']] 

任何想法如何有效地使它在Python?謝謝!

P.S.函數應該返回任何規模的名單輸入列表中的所有排列和組合,上述

回答

1

所示不僅僅是兩個元素的列表作爲一款全功能的方法,您可以使用permutations()product()chain()功能從itertools模塊和內置在功能map()

>>> from itertools import permutations, product, chain 
>>> def my_prod(lst): 
...  return product(*map(permutations, lst)) 
... 
>>> 
>>> list(chain(*map(my_prod, permutations(lst)))) 
[(('I1', 'I2', 'I3'), ('I2', 'I3')), (('I1', 'I2', 'I3'), ('I3', 'I2')), (('I1', 'I3', 'I2'), ('I2', 'I3')), (('I1', 'I3', 'I2'), ('I3', 'I2')), (('I2', 'I1', 'I3'), ('I2', 'I3')), (('I2', 'I1', 'I3'), ('I3', 'I2')), (('I2', 'I3', 'I1'), ('I2', 'I3')), (('I2', 'I3', 'I1'), ('I3', 'I2')), (('I3', 'I1', 'I2'), ('I2', 'I3')), (('I3', 'I1', 'I2'), ('I3', 'I2')), (('I3', 'I2', 'I1'), ('I2', 'I3')), (('I3', 'I2', 'I1'), ('I3', 'I2')), (('I2', 'I3'), ('I1', 'I2', 'I3')), (('I2', 'I3'), ('I1', 'I3', 'I2')), (('I2', 'I3'), ('I2', 'I1', 'I3')), (('I2', 'I3'), ('I2', 'I3', 'I1')), (('I2', 'I3'), ('I3', 'I1', 'I2')), (('I2', 'I3'), ('I3', 'I2', 'I1')), (('I3', 'I2'), ('I1', 'I2', 'I3')), (('I3', 'I2'), ('I1', 'I3', 'I2')), (('I3', 'I2'), ('I2', 'I1', 'I3')), (('I3', 'I2'), ('I2', 'I3', 'I1')), (('I3', 'I2'), ('I3', 'I1', 'I2')), (('I3', 'I2'), ('I3', 'I2', 'I1'))] 

這裏map函數映射在你的子列出了permutations然後product將創建置換的產品。

的另一種方式(稍微快),你可以用一個列表理解,而不是map()

>>> def my_prod(lst): 
...  return product(*[permutations(sub) for sub in lst]) 
+0

對不起,也許我的問題是不明確的,但在你的答案適用於在問題中給出的輸入列表,它不會返回列表的較長列表的所有排列和組合,例如'[['I1','I2','I3'],['I2','I3'],['I5',' I6']]' – madprogrammer

+0

@madprogrammer是的,檢出編輯。 – Kasramvd