给定一个列表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))...
答案 0 :(得分:7)
您可以使用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))]