在python中获取数组中所有成对组合的最快方法是什么?

Uts*_*kil 6 python arrays list

例如,如果数组是[1,2,3,4],我希望输出为[1,2],[1,3],[1,4],[2,3],[2,4] ]和[3,4].

我想要一个比使用两个for循环的强力方法更好的解决方案.我该如何实现?

bri*_*pck 18

虽然前面的答案将为您提供所有成对排序,但示例预期结果似乎意味着您需要所有无序对.

这可以通过以下方式完成itertools.combinations:

>>> import itertools
>>> x = [1,2,3,4]
>>> list(itertools.combinations(x, 2))
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
Run Code Online (Sandbox Code Playgroud)

与其他结果相比:

>>> list(itertools.permutations(x, 2))
[(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)]
Run Code Online (Sandbox Code Playgroud)


Moo*_*awr 5

import itertools

x = [1,2,3,4]

for each in itertools.permutations(x,2):
    print(each)
Run Code Online (Sandbox Code Playgroud)

请注意,itertools是一个生成器对象,这意味着您需要遍历它以获得所需的一切.'2'是可选的,但它告诉函数你想要的每个组合的数量是多少.

你可以在这里阅读更多

编辑:

正如ForceBru在评论中所说,你可以解压缩生成器进行打印,一起跳过for循环但是我仍然会遍历它,因为你可能不知道生成的对象有多大:

print(*itertools.permutations(x, 2))
Run Code Online (Sandbox Code Playgroud)

  • 在 Python 3.x 中可以执行 `print(*itertools.permutations(x, 2))`,它甚至更短。 (2认同)