为什么 map(print, a_list) 不起作用? [英] Why map(print, a_list) doesn't work?
问题描述
对于普通函数,map
效果很好:
For a normal function, map
works well:
def increment(n):
return n+1
l = [1, 2, 3, 4, 5]
l = map(increment, l)
print l
>>> [2, 3, 4, 5, 6]
但是,如果将 print
放在 map
函数中:
However, if it's print
being put inside the map
function:
l = [1, 2, 3, 4, 5]
l = map(print, l)
print l
python 会抱怨:
python will complain:
l = map(print, l)
^
SyntaxError: invalid syntax
是什么让 print
与众不同?print(x)
难道不是一个有效的函数调用吗?以上代码在python 2.7下测试.
What makes print
special? Doesn't print(x)
also a valid function call? The above code are tested under python 2.7.
推荐答案
在 Python 2.x 中,print
是一个语句,而不是一个函数.如果您在 Python 3.x 中尝试此操作,它将起作用.
In Python 2.x, print
is a statement, not a function. If you try this in Python 3.x it will work.
在 Python 2.x 中,您可以说 print(x)
,这不是语法错误,但实际上不是函数调用.正如 1 + (3)
与 1 + 3
相同,print(x)
与 print x<相同/code> 在 Python 2.x 中.
In Python 2.x, you can say print(x)
and it is not a syntax error, but it isn't actually a function call. Just as 1 + (3)
is the same as 1 + 3
, print(x)
is the same as print x
in Python 2.x.
在 Python 2.x 中,您可以这样做:
In Python 2.x you can do this:
def prn(x):
print x
然后你可以这样做:
map(prn, lst)
它会起作用.请注意,您可能不想做 lst = map(prn, lst)
因为 prn()
返回 None
,因此您将替换您的值列表具有相同长度的值列表 None
.
and it will work. Note that you probably don't want to do lst = map(prn, lst)
because prn()
returns None
, so you will replace your list of values with a same-length list of just the value None
.
Python 2.x 的另外两个解决方案
Two other solutions for Python 2.x.
如果你想彻底改变print
的行为,你可以这样做:
If you want to completely change the behavior of print
, you can do this:
from __future__ import print_function
map(print, lst)
这使得 print
成为一个函数,就像在 Python 3.x 中一样,因此它可以与 map()
一起使用.
This makes print
into a function just as it is in Python 3.x, so it works with map()
.
或者,您可以这样做:
from pprint import pprint
map(pprint, lst)
pprint()
是一个打印东西的函数,它可以作为内置函数使用.我不确定它与默认的 print
有什么不同(它说这是一个漂亮的打印"功能,但我不确定它到底有什么不同).
pprint()
is a function that prints things and it is available as a built-in. I'm not exactly sure how it is different from the default print
(it says it is a "pretty-print" function but I'm not sure how exactly that makes it different).
此外,根据 PEP 8 标准,不建议使用 l
作为变量名,因此我在示例中使用 lst
代替.
Also, according to the PEP 8 standard, it is non-recommended to use l
as a variable name, so I am using lst
instead in my examples.
http://www.python.org/dev/peps/pep-0008/
这篇关于为什么 map(print, a_list) 不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!