映射不同长度的迭代器 [英] Map on iterators of different length
本文介绍了映射不同长度的迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在回答此问题,并遇到以下问题:
I was answering this question and faced the following problem:
>>> from operator import add
>>> map(add,[1,2,3],[1,2])
Traceback (most recent call last):
File "<pyshell#47>", line 1, in <module>
map(add,[1,2,3],[1,2])
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
我希望map
在消耗完参数中提供的最小迭代器后立即停止.
I wanted map
to stop as soon as the smallest iterator provided in the parameters is consumed.
我找到了解决方法:
>>> from itertools import imap
>>> list(imap(add,[1,2,3],[1,2]))
[2, 4]
但是,为什么呢?他们的行为不应该一致吗?
But, why is that? Shouldn't their behavior be consistent?
这是解决问题的最好方法吗?
Is it the best way I workaround the problem?
推荐答案
如 itertools.imap
说明:
制作一个迭代器,该迭代器使用每个可迭代对象的参数来计算函数.如果将function设置为None,则imap()以元组形式返回参数. 与map()类似,但是在用尽最短的可迭代项时停止,而不是为较短的可迭代项填写None.造成这种差异的原因是,无限迭代器参数通常是map()的错误(因为对输出进行了完全评估),但代表了向imap()提供参数的常见且有用的方式.
这篇关于映射不同长度的迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文