python - Looking for an elegant way for looping simultaneously over two list with different lengths
问题描述
I'm looking for the most elegant/short/pythonic way to iterate through two uneven lists simultaneously. If the shorter list ends at some point, it should start to iterate from the beginning.
So far, I managed to do it with the while
, which I consider as ugly, and too long (from various reasons I need as short code as possible).
list1 = ["a", "b", "c"]
list2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
i1 = 0
i2 = 0
while True:
if i2 == len(list2):
break
if i1 == len(list1):
i1 = 0
print(list1[i1], list2[i2])
i1 += 1
i2 += 1
The expected result should look like this. I'm achieving it with while loop (the code above). But I need to have as short code as possible:
a 1
b 2
c 3
a 4
b 5
c 6
a 7
b 8
c 9
a 10
解决方案
zip
both lists, feeding the shortest one to itertools.cycle
so it repeats indefinitely (until list2
ends):
import itertools
list1 = ["a","b","c"]
list2 = [1,2,3,4,5,6,7,8,9,10]
for a,b in zip(itertools.cycle(list1),list2):
print(a,b)
prints:
a 1
b 2
c 3
a 4
b 5
c 6
a 7
b 8
c 9
a 10
(of course don't use itertools.zip_longest
as cycle
never ends, which would create an infinite loop)
推荐阅读
- python - 使用python计算平均总季节性降水量
- python - 如果列重复并且只取嵌套字典中的第一个列,则删除键值
- vue.js - 将图像 vuejs 传递给控制器 laravel
- apache-spark - 将 Spark 2.4 更新到 Spark 3.1 后出现 Spark/Kafka 错误
- python-3.x - 单元测试中的第二个功能没有运行
- wordpress - 为什么转换在我的情况下不起作用
- networking - 在 Mininet 中如何模拟 UDP 泛洪导致的丢包?
- node.js - Next.js API 路由 + Node-APN:无法获取 .p8 Apple 密钥文件的路径以在部署到 Vercel 后发送推送通知
- go-cd - 在所有其他任务完成后运行 GoCD 任务?
- linux - 为列(.CSV 文件)中的每个值生成 md5sum,然后将生成的 md5sum 值与已经给定的 md5sum 值进行比较