python中map()后为什么不能直接print()?

map()用法:

map(function, iterable, …)

function – 函数
iterable – 一个或多个序列


返回值:

Python 2.x 返回列表。
Python 3.x 返回迭代器。
所以Python 3.x要加list()函数将迭代器转化为列表。


我用的是python3,举例如下:

直接打印map()的返回值:

def f(x):
    return x*x

print(map(f, [1, 2, 3, 4, 5]))

运行结果:

>>> 
================== RESTART: C:/Users/18137/Desktop/Pfile/11.py =================
<map object at 0x000001DCA1AF1CC0>
>>> 
map()后再list()再打印:

def f(x):
    return x*x

print(list(map(f, [1, 2, 3, 4, 5])))

运行结果:

>>> 
================== RESTART: C:/Users/18137/Desktop/Pfile/11.py =================
[1, 4, 9, 16, 25]
>>> 

猜你喜欢

转载自blog.csdn.net/panlan7/article/details/124087512
今日推荐