[英]All pairs of pairs python
Given a list l=range(n)
, how can I iterate over all distinct pairs of distinct pairs from that list. 给定一个列表
l=range(n)
,我如何遍历该列表中不同对的所有不同对。
For example, if l = [0,1,2,3]
I would like [((0,1), (0,2)),((0,1),(0,3)), ((0,1),(1,2)), ((0,1), (1,3)),((0,1), (2,3)), ((0,2), (0,3)), ((0,2),(1,2)),((0,2),(1,3)),((0,2),(2,3))...
例如,如果
l = [0,1,2,3]
我想[((0,1), (0,2)),((0,1),(0,3)), ((0,1),(1,2)), ((0,1), (1,3)),((0,1), (2,3)), ((0,2), (0,3)), ((0,2),(1,2)),((0,2),(1,3)),((0,2),(2,3))...
You can use itertools.combinations
: 您可以使用
itertools.combinations
:
from itertools import combinations
for pair in combinations(combinations(l, 2), 2):
# use pair
The first call creates the initial pairs: 第一次调用将创建初始对:
>>> l = [0,1,2,3]
>>> list(combinations(l, 2))
[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
The second pairs them again: 第二对再次将它们配对:
>>> list(combinations(combinations(l, 2), 2))
[((0, 1), (0, 2)), ((0, 1), (0, 3)), ((0, 1), (1, 2)), ((0, 1), (1, 3)),
((0, 1), (2, 3)), ((0, 2), (0, 3)), ((0, 2), (1, 2)), ((0, 2), (1, 3)),
((0, 2), (2, 3)), ((0, 3), (1, 2)), ((0, 3), (1, 3)), ((0, 3), (2, 3)),
((1, 2), (1, 3)), ((1, 2), (2, 3)), ((1, 3), (2, 3))]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.