在 Itertools Recipes对于 Python 3.7 及更早版本,提到 padnone
“模拟内置 map() 函数的行为”:
def padnone(iterable):
"""Returns the sequence elements and then returns None indefinitely.
Useful for emulating the behavior of the built-in map() function.
"""
return chain(iterable, repeat(None))
虽然我了解 padnone
的用处,但我不明白它如何以任何方式模拟 map
。这是错误还是我遗漏了什么?
最佳答案
我认为该行已经过时 - 它尚未针对 map
的 Python 3 行为进行更新,或者 itertools.zip_longest
的存在.
map
可以采用多参数函数和多个可迭代的参数:
>>> from operator import add
>>> list(map(add, [1, 2], [10, 20]))
[11, 22]
回到Python 2,如果迭代器的长度不一样,较短的迭代器将用 None
填充。 :
>>> map(lambda x, y: [x, y], [1, 2], [10]) # Python 2
[[1, 10], [2, None]]
但是zip
和izip
当最短的可迭代停止时仍然会停止:
>>> zip([1, 2], [10]) # still Python 2
[(1, 10)]
>>> list(itertools.izip([1, 2], [10])) # still Python 2
[(1, 10)]
如果您想模拟map
的无填充行为在您自己的需要多个迭代的函数中,您可以使用 padnone
扩展较短的迭代。使用前zip
或izip
.
随着 itertools.izip_longest
的引入,这变得不太有用了Python 2.6 中提供了一种更方便、更安全的方式来填充此用例。与padnone
,您必须以某种方式预先知道哪些迭代更短并且需要填充;与 izip_longest
,不再需要了。
在 Python 3 中,map
不再None
-pads 默认情况下,所以填充并没有真正模拟 map
不再有。
关于python - 为什么文档提到 padnone 模拟内置 map 的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55961072/