lambda参数写法问题
今天看到一段程序中有用到lambda函数,其实很简单 key=lambda (l,s):s
猜我犯了个什么错误?
自己把(l,s)理解成lambda的2个形参了,是蛮容易这样理解的哈,毕竟以前函数都是 def f(1,s):这样的
然后自己调用时老提示错误,参数错误,于是就看了下官方文档才知道lmbda参数其实是这样的
lambda x,y:x+y
x,y是它的2个形参,所以这里 lambda (l,s)其实就只有一个参数,那就是一个tuple类型的参数,
所以调用时就是key((x,y))
这个错误是很容易犯啊;)
>>> key = lambda ( 1 ,s):s SyntaxError: invalid syntax >>> key = lambda (l,s) SyntaxError: invalid syntax >>> key = lambda (l,s):s >>> key <function < lambda > at 0x02A81CF0 > >>> key( 1 , 2 ) Traceback (most recent call last): File "<pyshell#6>" , line 1 , in <module> key( 1 , 2 ) TypeError: < lambda >() takes exactly 1 argument ( 2 given) >>> key( 1 ) Traceback (most recent call last): File "<pyshell#7>" , line 1 , in <module> key( 1 ) File "<pyshell#4>" , line 1 , in < lambda > key = lambda (l,s):s TypeError: 'int' object is not iterable >>> key([ 1 , 2 , 3 , 4 , 5 ]) Traceback (most recent call last): File "<pyshell#8>" , line 1 , in <module> key([ 1 , 2 , 3 , 4 , 5 ]) File "<pyshell#4>" , line 1 , in < lambda > key = lambda (l,s):s ValueError: too many values to unpack >>> key([ 1 ]) Traceback (most recent call last): File "<pyshell#9>" , line 1 , in <module> key([ 1 ]) File "<pyshell#4>" , line 1 , in < lambda > key = lambda (l,s):s ValueError: need more than 1 value to unpack >>> key([]) Traceback (most recent call last): File "<pyshell#10>" , line 1 , in <module> key([]) File "<pyshell#4>" , line 1 , in < lambda > key = lambda (l,s):s ValueError: need more than 0 values to unpack >>> key([], 1 ) Traceback (most recent call last): File "<pyshell#11>" , line 1 , in <module> key([], 1 ) TypeError: < lambda >() takes exactly 1 argument ( 2 given) >>> x = lambda (x,y):x + y >>> x( 1 , 2 ) Traceback (most recent call last): File "<pyshell#13>" , line 1 , in <module> x( 1 , 2 ) TypeError: < lambda >() takes exactly 1 argument ( 2 given) >>> x( 1 ) Traceback (most recent call last): File "<pyshell#14>" , line 1 , in <module> x( 1 ) File "<pyshell#12>" , line 1 , in < lambda > x = lambda (x,y):x + y TypeError: 'int' object is not iterable >>> x = lambda (x):x + 1 >>> x( 111 ) 112 >>> key = lambda x,y:x + y >>> key( 1 , 2 ) 3 >>> key = lambda ( 1 ,s):s SyntaxError: invalid syntax >>> key = lambda (l,s):s >>> key(( 1 , 2 )) 2 |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步