list元素的每个组合都没有替换

Lon*_*Rob 3 python

在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')

Del*_*gan 8

您正在寻找排列而不是组合.

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)

  • 文档通过显示`permutations()`可以用`product()`实现,删除重复,正是OP正在做的事情,从而巧妙地证实了这一点. (2认同)