【问题标题】:Is the Python map function a value-returning function?Python map 函数是返回值的函数吗?
【发布时间】:2018-06-08 11:56:47
【问题描述】:

我一直在尝试使用 Python 中的 map 函数,但遇到了一些麻烦。我不知道哪些是将函数 foo 映射到列表栏的正确方法:

map(foo, bar)

newBar = map(foo, bar)

我从不同的网站得到了不同的结果。以下哪个是正确的用法?

【问题讨论】:

    标签: python list return-type


    【解决方案1】:

    map 返回一个新列表,并且不会更改您在函数中输入的列表。所以,用法是:

    def foo(x): #sample function
        return x * 2
    
    bar = [1, 2, 3, 4, 5]
    newBar = map(foo, bar)
    

    在解释器中:

    >>> print bar
    [1, 2, 3, 4, 5]
    >>> print newBar
    [2, 4, 6, 8, 10]
    

    注意:这是python 2.x

    【讨论】:

      【解决方案2】:

      在 Python 2 中,map() 返回foo(...) 的返回值列表。如果您不关心结果而只想运行 barfoo 的元素,那么您的任何一个示例都可以工作。

      在 Python 3 中,map() 返回一个惰性求值的迭代器。您的两个示例都不会真正运行barfoo 的任何元素yet。您将需要迭代该迭代器。最简单的方法是将其转换为列表:

      list(map(foo, bar))
      

      【讨论】:

        【解决方案3】:

        在 Python 2 中,map() 返回一个新列表。在 Python 3 中,它返回一个迭代器。您可以将其转换为列表:

        new_list = list(map(foo, bar))
        

        顾名思义,迭代器的常见用途是对其进行迭代:

        for x in map(foo, bar):
            # do something with x
        

        这一次生成一个值,而不像创建列表那样将所有值都放入内存。

        此外,您可以通过迭代器执行单步操作:

        my_iter = map(foo, bar)
        first_value = next(my_iter)
        second_value = next(my_iter)
        

        现在与其余部分一起工作:

        for x in map(foo, bar):
            # x starts from the third value
        

        这在 Python 3 中很常见。zipenumerate 也返回迭代器。这通常称为惰性求值,因为只有在真正需要时才会产生值。

        【讨论】:

          猜你喜欢
          • 2020-08-17
          • 1970-01-01
          • 1970-01-01
          • 2019-02-12
          • 1970-01-01
          • 2010-09-08
          • 2014-02-19
          • 2018-04-09
          相关资源
          最近更新 更多