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

python中map()后为什么不能直接print,第1张

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()后再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]
>>> 

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/580769.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-11
下一篇 2022-04-11

发表评论

登录后才能评论

评论列表(0条)

保存