bin*_*bjz 2 python functional-programming python-3.x
>>> lst_ = [1]
>>> map(lambda x, y: x + y if y else 1, lst_, lst_[1:])
[1]
Run Code Online (Sandbox Code Playgroud)
>>> lst_ = [1]
>>> list(map(lambda x, y: x + y if y else 1, lst_, lst_[1:]))
[]
Run Code Online (Sandbox Code Playgroud)
我想知道为什么python2返回正确的结果,但python3返回None
我应该如何使用python3修改代码以返回正确的结果
这是对函数map()功能的更改(以及对成为迭代器的更改).因为输入现在是迭代器,所以map()已经更新以遵循相同的行为zip(),并且不会使用None值填充较短的输入.
如果一个iterable比另一个短,则假定用
None项目扩展.
使用Python 3版本:
对于多个迭代,迭代器在最短的iterable耗尽时停止.
您可以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:]))
Run Code Online (Sandbox Code Playgroud)
zip_longest()有一个额外的好处,你现在可以指定用作填充的值; 例如,您可以将其设置为0:
starmap(lambda x, y: x + y, zip_longest(lst_, lst_[1:], fillvalue=0))
Run Code Online (Sandbox Code Playgroud)
演示:
>>> 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]
Run Code Online (Sandbox Code Playgroud)