简体   繁体   English

在python中同时迭代多个列表

[英]Iterate over multiple lists simultaneously in python

I have a function that returns an element (elem) that are 3 lists (a,b,c) and I can do the following:我有一个函数,它返回一个元素(elem),它是 3 个列表(a、b、c),我可以执行以下操作:

for a,b,c in elem:
    do whatever...

Is there any way I can do the loop simultaneously with 2 of those elements?有什么方法可以同时使用其中两个元素进行循环吗? kind of something like this:有点像这样:

for a,b,c,d,e,f in elem1 and elem2:
    do whatever...

Well, assuming elem1 and elem2 have the same size.好吧,假设 elem1 和 elem2 具有相同的大小。

The zip function gives you the elements in pairs. zip函数为您提供成对的元素。

for (a, b, c), (d, e, f) in zip(elem1, elem2):
    do something...

You could also do it with indexes你也可以用索引来做

for i in range(len(elem1)):
    (a, b, c), (d, e, f) = elem1[i], elem2[i]
    do something...

You may iterate objects elem1 and elem2 together using zip function like this:您可以使用zip函数将对象 elem1 和 elem2 一起迭代,如下所示:

for (a,b,c),(d,e,f) in zip(elem1, elem2):
    do_whatever(a,b,c,d,e,f)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM