gpt4 book ai didi

python - 如何遍历列表的组合

转载 作者:太空狗 更新时间:2023-10-29 22:05:25 31 4
gpt4 key购买 nike

<分区>

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

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

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com