双迭代 [英] Double Iteration

查看:152
本文介绍了双迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

如何迭代两个列表 - python





<我希望同时迭代两个项目,在我看来这是一个迭代:

I want to iterate over two items at the same time, an iteration that in my mind looks like this:

for elem1 in list 1 and for elem2 in list2:
    do something to elem1; do something to elem2

然而,这种语法是不可接受的。为了清楚起见,我不是在谈论嵌套for循环,因为那时我将迭代第一个列表中每个元素的整个列表。我希望串联迭代两个列表(或其他)。有没有pythonic方式来做到这一点?

This syntax, however, is not acceptable. To be clear, I'm not talking about nested for loops, because then I'd be iterating over an entire list for every element in the first list. I want to iterate over the two lists (or whatever) in tandem. Is there a pythonic way to do this?

推荐答案

使用 zip()

for elem1, elem2 in zip(list1, list2):

如果其中一个列表是比另一个更长,你不会看到超出较短列表长度的元素。

If one of these lists is longer than the other, you won't see the elements beyond the length of the shorter list.

在python 2上, zip()会将两个列表的副本压缩在一起,以及可能成为内存负担的大型列表。使用 itertools.izip() 对于这样的较大列表,它返回一个迭代器。在python 3上, zip()本身已经返回一个迭代器。

On python 2, zip() results in a copy of both lists zipped together, and for large lists that can be a memory burden. Use itertools.izip() for such larger lists, it returns an iterator instead. On python 3, zip() itself already returns an iterator.

如果你需要遍历列表(并填写缺少的较短列表元素的填充值),使用 itertools.izip_longest() 代替:

If you need to loop over the longest list instead (and fill in a filler value for the missing shorter list elements), use itertools.izip_longest() instead:

from itertools import izip_longest

for elem1, elem2 in izip_longest(list1, list2):

这篇关于双迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆