Python lambda function printing <function <lambda> at 0x7fcbbc740668> instead of value

十年热恋 提交于 2019-12-01 05:45:43

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.

Ahsanul Haque

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) 

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)

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))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!