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

时间:2016-10-17 17:38:06

标签: python arrays list

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

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

2 个答案:

答案 0 :(得分:11)

虽然前面的答案会给出所有成对排序,但示例预期结果似乎暗示您需要所有无序对。

可以使用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)]

与其他结果比较:

>>> 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)]

答案 1 :(得分:5)

import itertools

x = [1,2,3,4]

for each in itertools.permutations(x,2):
    print(each)

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

You can read more here

编辑:

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

print(*itertools.permutations(x, 2))