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']


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM