在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')]
Run Code Online (Sandbox Code Playgroud)
目前我这样做:
[x for x in itertools.product(foo, repeat=2) if x[0] != x[1]]
Run Code Online (Sandbox Code Playgroud)
但我怀疑有一个内置的方法.它是什么?
注意: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')]
Run Code Online (Sandbox Code Playgroud)