代码之家  ›  专栏  ›  技术社区  ›  Amit Rastogi

当使用python函数映射(fun,iter)时何时调用“fun”[重复]

  •  0
  • Amit Rastogi  · 技术社区  · 7 年前

    为什么下面的代码不打印任何内容:

    #!/usr/bin/python3
    class test:
        def do_someting(self,value):
            print(value)
            return value
    
        def fun1(self):
            map(self.do_someting,range(10))
    
    if __name__=="__main__":
        t = test()
        t.fun1()
    

    我在Python 3中执行上述代码。我想我错过了一些很基本的东西,但是我想不出来。

    0 回复  |  直到 9 年前
        1
  •  38
  •   Martijn Pieters    11 年前

    map() returns an iterator ,并且在您请求之前不会处理元素。

    将其转换为列表以强制处理所有元素:

    list(map(self.do_someting,range(10)))
    

    或使用 collections.deque()

    from collections import deque
    
    deque(map(self.do_someting, range(10)))
    

    但请注意,只需使用 for

    for i in range(10):
        self.do_someting(i)
    
        2
  •  4
  •   bootchk    12 年前

    在Python3之前,map()返回的是一个列表,而不是迭代器。因此,您的示例将在Python2.7中工作。

    list()通过迭代其参数来创建新列表。(list()不仅仅是从元组到列表的类型转换。所以list(list((1,2))返回[1,2]。)所以list(map(…)与Python2.7向后兼容。

        3
  •  1
  •   Grief    12 年前

    我只想补充一下:

    With multiple iterables, the iterator stops when the shortest iterable is exhausted https://docs.python.org/3.4/library/functions.html#map ]

    >>> list(map(lambda a, b: [a, b], [1, 2, 3], ['a', 'b']))
    [[1, 'a'], [2, 'b'], [3, None]]
    

    Python 3.4.0(默认值,2014年4月11日,13:05:11)

    >>> list(map(lambda a, b: [a, b], [1, 2, 3], ['a', 'b']))
    [[1, 'a'], [2, 'b']]
    

    这种差异使得简单包装的答案 list(...) 不完全正确

    同样可以通过以下方式实现:

    >>> import itertools
    >>> [[a, b] for a, b in itertools.zip_longest([1, 2, 3], ['a', 'b'])]
    [[1, 'a'], [2, 'b'], [3, None]]