代码之家  ›  专栏  ›  技术社区  ›  Olivier Melançon iacob

为什么文档提到padnone模仿内置map的行为?

  •  1
  • Olivier Melançon iacob  · 技术社区  · 5 年前

    Itertools Recipes 对于python3.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))
    

    虽然我明白 帕德农 模仿 map

    0 回复  |  直到 5 年前
        1
  •  5
  •   user2357112    5 年前

    我认为这一行已经过时了-它还没有针对python3的行为进行更新 map 或者为了 itertools.zip_longest

    地图 可以采用多参数函数和多个参数的Iterable:

    >>> from operator import add
    >>> list(map(add, [1, 2], [10, 20]))
    [11, 22]
    

    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)]
    

    地图 padnone 使用前 .

    随着 itertools.izip_longest 在Python2.6中,它提供了一种更方便、更安全的填充方式。与 izip_longest ,这不再是必要的。

    在Python 3中, 地图 没有 -默认情况下是pads,所以padding不是真正的模拟 再。