如何使用 Python 3 打印地图对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44461551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 00:02:14  来源:igfitidea点击:

How to print map object with Python 3?

pythonpython-3.x

提问by MishaVacic

This is my code

这是我的代码

def fahrenheit(T):
    return ((float(9)/5)*T + 32)

temp = [0, 22.5, 40,100]
F_temps = map(fahrenheit, temp)

This is mapobject so I tried something like this

这是 mapobject 所以我尝试了这样的事情

for i in F_temps:
    print(F_temps)

<map object at 0x7f9aa050ff28>
<map object at 0x7f9aa050ff28>
<map object at 0x7f9aa050ff28>
<map object at 0x7f9aa050ff28>

I am not sure but I think that my solution was possible with Python 2.7,how to change this with 3.5?

我不确定,但我认为我的解决方案可以使用 Python 2.7,如何使用 3.5 更改它?

回答by CodelessBugging

You have to turn the map into a list or tuple first. To do that,

您必须先将地图转换为列表或元组。要做到这一点,

print(list(F_temps))

This is because maps are lazily evaluated, meaning the values are only computed on-demand. Let's see an example

这是因为地图是惰性计算的,这意味着这些值仅按需计算。让我们看一个例子

def evaluate(x):
    print(x)

mymap = map(evaluate, [1,2,3]) # nothing gets printed yet
print(mymap) # <map object at 0x106ea0f10>

# calling next evaluates the next value in the map
next(mymap) # prints 1
next(mymap) # prints 2
next(mymap) # prints 3
next(mymap) # raises the StopIteration error

When you use map in a for loop, the loop automatically calls nextfor you, and treats the StopIteration error as the end of the loop. Calling list(mymap)forces all the map values to be evaluated.

当您在 for 循环中使用 map 时,循环会自动调用next您,并将 StopIteration 错误视为循环结束。调用list(mymap)强制评估所有地图值。

result = list(mymap) # prints 1, 2, 3

However, since our evaluatefunction has no return value, resultis simply [None, None, None]

然而,由于我们的evaluate函数没有返回值,result只是[None, None, None]