Skip to main content
 首页 » 编程设计

python之所有成对的 python

2025年05月04日16虾米姐

给定一个列表 l=range(n),我如何遍历该列表中所有不同对的不同对。

例如,如果 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))...

请您参考如下方法:

您可以使用 itertools.combinations :

from itertools import combinations 
 
for pair in combinations(combinations(l, 2), 2): 
    # use pair 

第一次调用创建初始对:

>>> l = [0,1,2,3] 
>>> list(combinations(l, 2)) 
[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)] 

第二个再次配对:

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