Iterate over two list of different sizes in python

被刻印的时光 ゝ 提交于 2019-12-08 03:46:57

问题


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

what I am Looking for is :

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


回答1:


You can use itertools.cycle with zip instead:

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)

This outputs:

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


来源:https://stackoverflow.com/questions/51375231/iterate-over-two-list-of-different-sizes-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!