对于Python 2.7.13
>>> lst_ = [1]
>>> map(lambda x, y: x + y if y else 1, lst_, lst_[1:])
[1]
对于Python 3.6.1
>>> lst_ = [1]
>>> list(map(lambda x, y: x + y if y else 1, lst_, lst_[1:]))
[]
两个问题:
我想知道为什么python2返回正确的结果,而python3返回None
如何用python3修改代码才能返回正确的结果
最佳答案
这是对 map()
函数功能的更改(以及成为迭代器的更改)。由于输入现在是迭代器,因此 map()
已更新为遵循与 zip()
相同的行为,并且不会用以下内容填充较短的输入无
值。
比较documentation for map()
in Python 2 :
If one iterable is shorter than another it is assumed to be extended with
None
items.
与 Python 3 version :
With multiple iterables, the iterator stops when the shortest iterable is exhausted.
您可以使用itertools.zip_longest()
与 itertools.starmap()
一起再次获得 Python 2 行为:
from itertools import starmap, zip_longest
starmap(lambda x, y: x + y if y else 1, zip_longest(lst_, lst_[1:]))
zip_longest()
还有一个额外的优点,您现在可以指定用作填充符的值;例如,您可以将其设置为 0
:
starmap(lambda x, y: x + y, zip_longest(lst_, lst_[1:], fillvalue=0))
演示:
>>> from itertools import starmap, zip_longest
>>> lst_ = [1]
>>> list(starmap(lambda x, y: x + y if y else 1, zip_longest(lst_, lst_[1:])))
[1]
>>> list(starmap(lambda x, y: x + y, zip_longest(lst_, lst_[1:], fillvalue=0)))
[1]
关于python3 : Using ternary operator in map, 它将返回 None,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44525583/