【发布时间】:2019-09-25 08:30:24
【问题描述】:
在 python 中,并行迭代到迭代器的惯用方式是使用“zip”函数。
Python 3.6.5 (default, Mar 31 2018, 19:45:04) [GCC] on linux
>>> it1 = range(0,5)
>>> it2 = range(3,10)
>>> for x1, x2 in zip(it1, it2): print('', x1, x2, sep='\t')
...
0 3
1 4
2 5
3 6
4 7
>>> it1 = range(0,5)
>>> it2 = range(3,10)
>>> [ 100*x1 + x2 for x1,x2 in zip(it1,it2) ]
[3, 104, 205, 306, 407]
但是,我不喜欢这里的模式,它将项目到名称的分配与压缩迭代中的项目顺序分离:在更复杂的示例中,可能很容易产生诸如
之类的错误for apple1, apple2, orange in zip(apples, oranges, more_apples): ...
因此我想知道是否存在一种模式,它允许类似于
for apple1 in apples,\
apple2 in oranges,\
orange in more_apples: ...
这样的错误会更明显。
对于列表推导,存在外观相似的语法,但对应于 itertools.product() 而不是 zip()。
【问题讨论】:
-
作为与问题无关的评论:
it1 = range(0,5)之类的行不必多次使用,因为它们不是生成器,并且不会筋疲力尽。至于您的问题,解决方法是在第一个列表上使用 enumerate,并通过索引从其他列表中获取元素。 -
我想使用
for i in range(len(apples)): apples[i], oranges[i], ...是一种选择,但处理不同的长度不会像使用zip那样优雅。 -
@Chris 如果苹果、橙子是迭代器(不能被索引)并且预期的元素数量使得包装到可索引容器中不可行,它也不起作用。
-
投反对票时,请评论为什么。
标签: python iterator iteration generator