How to iterate through two lists in parallel?(如何并行遍历两个列表?)
问题描述
我在 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 range(len(foo)):
print("f: ", foo[i], "; b: ", bar[i])
但这对我来说似乎有些不合时宜.有没有更好的方法?
But that seems somewhat unpythonic to me. Is there a better way to do it?
推荐答案
Python 3
for f, b in zip(foo, bar):
print(f, b)
zip 在 foo 或 bar 中较短者停止时停止.
zip stops when the shorter of foo or bar stops.
在 Python 3 中,zip代码>返回元组的迭代器,如 Python2 中的 itertools.izip.获取列表元组,使用 list(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.
在 Python 2 中,zip代码>返回一个元组列表.当 foo 和 bar 不是很大时,这很好.如果它们都是巨大的,那么形成 zip(foo,bar) 是不必要的巨大临时变量,应替换为 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 用尽时停止.当 foo 和 bar 都用尽时,izip_longest 停止.当较短的迭代器用尽时,izip_longest 会产生一个元组,其中 None 在对应于该迭代器的位置.您还可以根据需要设置除 None 之外的其他 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.
还要注意 zip 及其类似 zip 的 brethen 可以接受任意数量的可迭代对象作为参数.例如,
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
这篇关于如何并行遍历两个列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何并行遍历两个列表?
基础教程推荐
- 尝试制作WhatsApp机器人 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
