列表元素的每个排列(无替换)[重复]

问题描述 投票:0回答:1

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

python combinations python-itertools combinatorics
1个回答
10
投票

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

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')]
© www.soinside.com 2019 - 2024. All rights reserved.