给定一个列表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))]

关于python - 所有成对的python,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21115122/

10-12 22:44