2015-09-08 29 views
3

在Python 2.7中,我想獲取列表元素的self-cartesian product,但沒有元素與自身配對。列表元素的每種組合都無需替換

In[]: foo = ['a', 'b', 'c'] 
In[]: [x for x in itertools.something(foo)] 
Out[]: 
     [('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')] 

目前我做的:

[x for x in itertools.product(foo, repeat=2) if x[0] != x[1]] 

,但我懷疑有一個內置的方法這一點。它是什麼?

注:itertools.combinationswouldn't give me('a', 'b')('b', 'a')

回答

8

您正在尋找permutations,而不是組合。

from itertools import permutations 

foo = ['a', 'b', 'c'] 
print(list(permutations(foo, 2))) 

# Out: [('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')] 
+2

該文檔通過顯示'permutations()'可以通過'product()'來實現,並重復刪除,完全符合OP的要求。 –