Python 3 Map 函数不是调用函数 [英] Python 3 Map function is not Calling up function

查看:27
本文介绍了Python 3 Map 函数不是调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么下面的代码不打印任何东西:

Why doesn't following code print anything:

#!/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 中执行上述代码.我想我遗漏了一些非常基本但无法弄清楚的东西.

I'm executing the above code in Python 3. I think i'm missing something very basic but not able to figure it out.

推荐答案

map() 返回一个迭代器,并且在您要求之前不会处理元素.

map() returns an iterator, and will not process elements until you ask it to.

把它变成一个列表,强制处理所有元素:

Turn it into a list to force all elements to be processed:

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

或使用 collections.deque() 并将长度设置为 0 以在不需要地图输出时不生成列表:

or use collections.deque() with the length set to 0 to not produce a list if you don't need the map output:

from collections import deque

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

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

but note that simply using a for loop is far more readable for any future maintainers of your code:

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

这篇关于Python 3 Map 函数不是调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆