Map on iterators of different length

空扰寡人 提交于 2019-12-07 12:55:17

问题


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'

I wanted map to stop as soon as the smallest iterator provided in the parameters is consumed.

I found the solution:

>>> 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?


回答1:


As described on the itertools.imap description:

Make an iterator that computes the function using arguments from each of the iterables. If function is set to None, then imap() returns the arguments as a tuple. Like map() but stops when the shortest iterable is exhausted instead of filling in None for shorter iterables. The reason for the difference is that infinite iterator arguments are typically an error for map() (because the output is fully evaluated) but represent a common and useful way of supplying arguments to imap().




回答2:


What about: map(sum, zip([1,2,3],[4,5]))?



来源:https://stackoverflow.com/questions/13348263/map-on-iterators-of-different-length

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!