python - 如何遍历列表的组合

标签 python list iterator

<分区>

我有一个元素列表,比如说

list = [1, 2, 3, 4]

我想遍历这个列表中的几个不同元素,所以

for x, y in some_iterator(list):
    print x, y

应该显示

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

请注意,我不想要所有 list 的组合,如 this question .只是给定长度的组合。

执行此操作的最 pythonic 方法是什么?


如果我想对 n-uples 做同样的事情怎么办?例如 n

3 元素的组合
for x, y, z in another_iterator(list):
    print x, y, z

会显示

1 2 3
1 2 4
2 3 4

最佳答案

使用itertools.combinations :

from itertools import combinations

for combo in combinations(lst, 2):  # 2 for pairs, 3 for triplets, etc
    print(combo)

关于python - 如何遍历列表的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41680388/

相关文章:

python - 引用单行树中的各个字典

Python 跳过迭代器

python - 如何在 conda env 中重用全局站点包

python - 非常简单的 python 客户端/服务器工作,但奇怪的延迟

list - ALV 列表中的两级列标题

c++ - 如何使用迭代器?

python - zip(*[iter(s)]*n) 在 Python 中是如何工作的?

python - 使用 GAE 数据存储进行作业管理

python - 如何使反斜杠 (\) 在 IDLE 中工作?

Java JList和列表问题