Python3映射函数未调用函数

2024-09-27 07:33:38 发布

您现在位置:Python中文网/ 问答频道 /正文

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

#!/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中执行上述代码。我想我错过了一些很基本的东西,但是我想不出来。


Tags: 代码testself内容returnbinvalueusr
3条回答

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

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

^{} returns an iterator,并且在您请求之前不会处理元素。

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

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

或者,如果不需要映射输出,使用长度设置为0的collections.deque()不生成列表:

from collections import deque

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

但是请注意,对于代码的任何未来维护者来说,简单地使用for循环更具可读性:

for i in range(10):
    self.do_someting(i)

我只想补充一下:

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

Python 2.7.6(默认值,2014年3月22日,22:59:56)

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

相关问题 更多 >

    热门问题