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

时间:2015-09-08 10:58:19

标签: python

在Python 2.7中,我想获得列表元素的self-cartesian product,但没有元素与自身配对。

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

目前我这样做:

itertools.combinations

但我怀疑这是一种内置的方法。它是什么?

注意:('a', 'b') wouldn't give me ('b', 'a')i=0

1 个答案:

答案 0 :(得分: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')]
相关问题