在 Python 2.7 中,我想获得列表元素的自笛卡尔积,但没有与自身配对的元素。
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.combinations
不会给我('a', 'b')
和('b', 'a')
您正在寻找排列而不是组合。
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')]