python3 : Using ternary operator in map, 它将返回 None

标签 python python-3.x functional-programming

对于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/

相关文章:

python - 用随机生成的数字替换字符串的一部分

python - 为什么我不能在 pyttsx3 中改变声音?

functional-programming - 寻找函数式编程词典

r - 如何使用嵌套数据框整理数据?

python - 什么是 co_names?

python - 寻找最大的重复子串

python - 什么会导致 IOError : bad message length

python - 子类是否需要初始化一个空的父类(super class)?

python-3.x - Keras NN 损失没有减少

scala - 函数式 Scala 中的选择排序