如何并行迭代两个列表? [英] How to iterate through two lists in parallel?

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

问题描述

我在Python中有两个迭代,我想成对检查它们:

I have two iterables in Python, and I want to go over them in pairs:

foo = (1, 2, 3)
bar = (4, 5, 6)

for (f, b) in some_iterator(foo, bar):
    print "f: ", f, "; b: ", b

它应该导致:

f: 1; b: 4
f: 2; b: 5
f: 3; b: 6

一种方式是迭代索引:

for i in xrange(len(foo)):
    print "f: ", foo[i], "; b: ", b[i]

但这对我来说似乎有点不合理。有没有更好的方法呢?

But that seems somewhat unpythonic to me. Is there a better way to do it?

推荐答案

for f, b in zip(foo, bar):
    print(f, b)

zip foo bar 中的较短者停止时停止。

zip stops when the shorter of foo or bar stops.

Python 2 中, zip
返回元组列表。当 foo bar 不是很大时,这很好。如果
它们都很大,那么形成 zip(foo,bar)是一个不必要的巨额
临时变量,应该用<$ c $替换c> itertools.izip 或
itertools.izip_longest ,它返回迭代器而不是列表。

In Python 2, zip returns a list of tuples. This is fine when foo and bar are not massive. If they are both massive then forming zip(foo,bar) is an unnecessarily massive temporary variable, and should be replaced by itertools.izip or itertools.izip_longest, which returns an iterator instead of a list.

import itertools
for f,b in itertools.izip(foo,bar):
    print(f,b)
for f,b in itertools.izip_longest(foo,bar):
    print(f,b)

izip foo bar 时停止很累。
izip_longest foo bar 时停止筋疲力尽
当较短的迭代器耗尽时, izip_longest 在对应的位置产生一个的元组到那个迭代器。如果您愿意,还可以在之外设置不同的 fillvalue 。请参阅此处了解全文

izip stops when either foo or bar is exhausted. izip_longest stops when both foo and bar are exhausted. When the shorter iterator(s) are exhausted, izip_longest yields a tuple with None in the position corresponding to that iterator. You can also set a different fillvalue besides None if you wish. See here for the full story.

Python 3 中, zip
返回元组的迭代器,如Python2中的 itertools.izip 。要获得
元组的列表,请使用列表(zip(foo,bar))。压缩到两个迭代器都耗尽
,你会使用
itertools.zip_longest

In Python 3, zip returns an iterator of tuples, like itertools.izip in Python2. To get a list of tuples, use list(zip(foo, bar)). And to zip until both iterators are exhausted, you would use itertools.zip_longest.

另请注意 zip 及其 zip -like brethen可以接受任意数量的iterables作为参数。例如,

Note also that zip and its zip-like brethen can accept an arbitrary number of iterables as arguments. For example,

for num, cheese, color in zip([1,2,3], ['manchego', 'stilton', 'brie'], 
                              ['red', 'blue', 'green']):
    print('{} {} {}'.format(num, color, cheese))

打印

1 red manchego
2 blue stilton
3 green brie

这篇关于如何并行迭代两个列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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