python学习--如何在一个for循环中迭代多个可迭代对象(串行,并行)

并行,使用zip函数。

l1=['1','2','3','4','5']
l2=['a','b','c','d','e']
l3=['qqq','www','eee','rrr','ttt']
l4=zip(l1,l2,l3)
for x,y,z in l4:
  print(x,y,z)
print(list(zip(l1,l2,l3)))   #[('1', 'a', 'qqq'), ('2', 'b', 'www'), ('3', 'c', 'eee'), ('4', 'd', 'rrr'), ('5', 'e', 'ttt')]

串行:使用itertools下的chain函数

from itertools import chain
l1=['1','2','3','4','5']
l2=['a','b','c','d','e']
l3=['qqq','www','eee','rrr','ttt']
l4=chain(l1,l2,l3)
for x in l4:
  print(x)
print(list(chain(l1,l2,l3)))    #['1', '2', '3', '4', '5', 'a', 'b', 'c', 'd', 'e', 'qqq', 'www', 'eee', 'rrr', 'ttt']

原文地址:https://www.cnblogs.com/daacheng/p/7932721.html