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

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

问题描述

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

 #!/ usr / bin / python3 
class test :
def do_someting(self,value):
print(value)
返回值
$ b def fun1(self):
map(self.do_someting ,范围(10))

if __name __ ==__ main__:
t = test()
t.fun1()

我在Python 3中执行上述代码。我想我错过了一些非常基本的东西,但无法弄清楚。

解决方案

map()返回一个迭代器,并且不会处理元素,直到您提出要求。



  list(map(self.do_someting,range(10))将列表转换为列表以强制处理所有元素: )))

或使用 collections.deque()长度设置为0不会产生列表,如果你d不需要map输出:

  from集合import deque 

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

但是请注意,只需使用 循环对未来的代码维护者来说更具可读性:

  ):
self.do_someting(i)


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

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

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

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天全站免登陆