gpt4 book ai didi

python - 没有替换的列表元素的每个组合

转载 作者:太空宇宙 更新时间:2023-11-03 12:58:15 24 4
gpt4 key购买 nike

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

 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 wouldn't give me ('a', 'b')('b', 'a')

最佳答案

您正在寻找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')]

关于python - 没有替换的列表元素的每个组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32455990/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com