问题
I am a beginner in python, and I was playing around with lambda functions. I was writing a program using lambda function to print characters that are +1 the ascii value of the input characters. My code is
#!/usr/bin/python
import sys
try:
word = sys.argv[1]
except:
print "No arguments passed"
sys.exit(1)
def convert_ascii(char):
return "".join(chr(ord(char) + 1))
for i in word:
print convert_ascii(i)
print lambda x: chr(ord(i) + 1)
I have a function convert_ascii that does the same thing as lambda. However, my output is
/usr/bin/python2.7 /home/user1/PycharmProjects/test/Tut1/asciipl2.py "abc def ghi"
b
<function <lambda> at 0x7f0310160668>
c
<function <lambda> at 0x7f0310160668>
d
<function <lambda> at 0x7f0310160668>
!
<function <lambda> at 0x7f0310160668>
e
<function <lambda> at 0x7f0310160668>
f
<function <lambda> at 0x7f0310160668>
g
<function <lambda> at 0x7f0310160668>
!
<function <lambda> at 0x7f0310160668>
h
<function <lambda> at 0x7f0310160668>
i
<function <lambda> at 0x7f0310160668>
j
<function <lambda> at 0x7f0310160668>
The purpose of this script is learning lambda, though there are other ways to do this program. Please let me know what am I doing wrong. Process finished with exit code 0
回答1:
You aren't calling the function. It's the same as if you wrote
print convert_ascii
instead of print convert_ascii(i)
.
Try
print (lambda x: chr(ord(x) + 1))(i)
Note that I changed ord(i)
to ord(x)
in the function body.
回答2:
Currently you are printing a function object. You have to call the function.
Receive the function in a variable and call it with a parameter.
for i in word:
print convert_ascii(i)
fun=lambda x: chr(ord(x) + 1)
print fun(some_arg)
回答3:
The Lambda Keyword returns an anonymous function:
>>> func = lambda x: x+1
>>> print(func)
<function <lambda> at 0x7f0310160668>
the above is (not counting behing-the-scenes magic) equivalent to:
>>> def func(x):
return x+1
>>> print(func)
<function func at 0x7fa73d3e6bf8>
to invoke the function, lambda or not, you still have to call it:
>>> print(func)
<function <lambda> at 0x7f0310160668>
>>> func(123)
124
That said, Lambdas are not very well suited to this situation, and are better used if a function or construct requires a short function.
>>> word = "spam"
>>> map(lamda x: chr(ord(x) + 1), word)
回答4:
You are trying to print the function itself. Instead of that, assign the function in a variable, and pass the parameter to the variable, or use the same within print itself.
for i in word:
z = lambda x: chr(ord(x) + 1)
print z(i)
or
for i in word:
print (lambda x: chr(ord(x) + 1))(i)
or to learn map, you can use map to get the same result
for i in word:
print "".join(map(lambda x: chr(ord(x) + 1), i))
来源:https://stackoverflow.com/questions/32670130/python-lambda-function-printing-function-lambda-at-0x7fcbbc740668-instead-of