Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何遍历两个列表?_Python_Loops - Fatal编程技术网

Python 如何遍历两个列表?

Python 如何遍历两个列表?,python,loops,Python,Loops,在我的python代码中,我有两个iterable列表 num = [1, 2, 3 ,4 ,5 ,6 ,] alpa = ['a', 'b', 'c', 'd'] for (a, b) in itertools.izip_longest(num, alpa): print a, b 输出: 1A 2 b 3 c 4d 5无 6无 我的预期产出: 1A 2 b 3 c 4d 5 a 6b 如何实现它?您可以使用itertools.cycle。下面是一些Python 3代码。请注

在我的python代码中,我有两个iterable列表

num = [1, 2, 3 ,4 ,5 ,6 ,]

alpa = ['a', 'b', 'c', 'd']

for (a, b) in itertools.izip_longest(num, alpa):

   print a, b
输出:

1A
2 b
3 c
4d
5无
6无
我的预期产出:

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

如何实现它?

您可以使用
itertools.cycle
。下面是一些Python 3代码。请注意,使用的是
zip
,而不是
izip_longest
,因为
cycle
创建了一个无限迭代器,您希望在一个列表完成时停止

import itertools

num = [1, 2, 3, 4, 5, 6] 

alpa = ['a', 'b', 'c', 'd'] 

for (a, b) in zip(num, itertools.cycle(alpa)):

   print(a, b)

答案如下:使用
itertools.cycle
@Barmar:你有一个python金徽章。为什么你的投票不能重复结束?@Bazingaa昨晚很忙,达到了极限。很好,谢谢:)