在python中遍历两个不同大小的列表 [英] Iterate over two list of different sizes in python

查看:90
本文介绍了在python中遍历两个不同大小的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Value = [1,2,3,4,5,6]
content = ['a','b','c','d']

for a,b in itertools.zip_longest(Value , content):
   print(a,b)

我使用上面的代码获得的输出如下:

The Output that i get using the above code is as follows:

1 a
2 b
3 c
4 d
5 None
6 None

我正在寻找的是:

1 a
2 b
3 c
4 d
5 a
6 b

基本上,一旦一个列表用完,它应该从开始重新取值.如果有人可以帮助的话,那就意味着很多

basically once one list is exhausted it should take the values again from starting. if any one could help would mean alot

推荐答案

您可以将itertools.cyclezip结合使用:

import itertools
Value = [1,2,3,4,5,6]
content = ['a','b','c','d']

for a,b in zip(Value , itertools.cycle(content)):
   print(a,b)

这将输出:

1 a
2 b
3 c
4 d
5 a
6 b

这篇关于在python中遍历两个不同大小的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆