简体   繁体   English

在 python 中打印不可转换为列表的 map object 的结果

[英]Printing the result of a map object in python that is not convertible to list

I was attempting to try out map function and end up with the following:我试图尝试 map function 并最终得到以下结果:

x=[1,2,-3,4]
result=(map(sum,x))
print(list(result))

Result:结果:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-19-5270e85794e8> in <module>
      1 result=(map(sum,x))
----> 2 print(list(result))

TypeError: 'int' object is not iterable

I understand the reason for the error above but please help me with how to print the result.我理解上述错误的原因,但请帮助我如何打印结果。

map does a delayed execution, so when you cast the result to a list, the map is executed, which amounts in computing sum(1) , sum(2) , sum(-3) and sum(4) map 执行延迟,因此当您将结果转换为列表时,将执行 map,这相当于计算sum(1)sum(2)sum(-3)sum(4)

Any of those will fail because sum takes something like a list (an iterable object) in input.任何这些都将失败,因为 sum 在输入中需要类似列表(可迭代对象)的东西。 You pass integers which are not iterable, hence the error message.您传递不可迭代的整数,因此会出现错误消息。

As suggested in the comments, you want to do a simple sum(x) .正如评论中所建议的,您想做一个简单的sum(x)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM