在Python中遍历列表中的每两个元素

3

如何在列表中迭代所有的配对组合,例如:

list = [1,2,3,4]

输出:

1,2
1,3
1,4
2,3
2,4
3,4

谢谢!


使用for循环和切片? - fredtantini
3个回答

4

使用itertools.combinations

>>> import itertools
>>> lst = [1,2,3,4]
>>> for x in itertools.combinations(lst, 2):
...     print(x)
...
(1, 2)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(3, 4)

顺便提醒,不要使用list作为变量名。它会掩盖内置的函数/类型list


1
使用 itertools.combinations
>>> import itertools
>>> list(itertools.combinations([1,2,3,4], 2))
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]

-2
你可以使用嵌套的for循环,如下所示:
list = [1,2,3,4]
for x in list :

    for y in list :

        print x, y

3
这将产生笛卡尔积(例如,你会得到(1,1)、(3,1)和(4,4))。 - DSM

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接