从列表中获取所有成对组合 [英] Get all pairwise combinations from a list
本文介绍了从列表中获取所有成对组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,如果输入列表为
[1, 2, 3, 4]
我希望输出为
[[1,2], [1,3], [1,4], [2,3], [2,4], [3,4]]
如果可能的话,我想要一个比使用两个for循环的强力方法更好的解决方案.我该如何实现?
If possible, I would like a solution which is better than the brute force method of using two for loops. How do I implement this?
推荐答案
尽管先前的答案将为您提供所有成对的排序,但是示例预期结果似乎暗示您希望所有无序对.
Though the previous answer will give you all pairwise orderings, the example expected result seems to imply that you want all unordered pairs.
这可以通过 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)]
这篇关于从列表中获取所有成对组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文