gpt4 book ai didi

python - 如何并行迭代两个列表?

转载 作者:太空宇宙 更新时间:2023-11-03 21:13:44 25 4
gpt4 key购买 nike

我有两个可迭代对象,我想成对地检查它们:

foo = [1, 2, 3]
bar = [4, 5, 6]

for (f, b) in iterate_together(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])

但这对我来说似乎有些不合时宜。有更好的方法吗?

<小时/>

相关任务:
<子>* How to merge lists into a list of tuples? - 给定上面的 foobar,创建列表 [(1, 4), (2, 5), (3, 6)].
<子>* How can I make a dictionary (dict) from separate lists of keys and values? - 创建字典 {1: 4, 2: 5, 3: 6}
<子>* Create a dictionary with comprehension - 在字典理解中使用 zip 构造 dict

最佳答案

Python 3

for f, b in zip(foo, bar):
print(f, b)
foobar 中较短者停止时,

zip 停止。

Python 3中,zip返回元组的迭代器,如 Python2 中的 itertools.izip 。获取列表对于元组,请使用 list(zip(foo, bar))。并压缩直到两个迭代器都完成筋疲力尽,你会用 itertools.zip_longest .

Python 2

Python 2中,zip返回元组列表。当 foobar 规模不大时,这很好。如果它们都很大,那么形成 zip(foo,bar) 是不必要的巨大临时变量,应替换为 itertools.izipitertools.izip_longest,它返回一个迭代器而不是列表。

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)
foobar 耗尽时,

izip 停止。当 foobar 都耗尽时,izip_longest 停止。当较短的迭代器耗尽时,izip_longest 会生成一个在与该迭代器对应的位置具有 None 的元组。如果您愿意,您还可以设置除 None 之外的不同 fillvalue。请参阅此处的 full story .

<小时/>

另请注意,zip 及其类似 zip 的 brethen 可以接受任意数量的可迭代对象作为参数。例如,

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

关于python - 如何并行迭代两个列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54862692/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com