zoukankan      html  css  js  c++  java
  • 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
    
  • 相关阅读:
    iOS截取http/https流量
    Jenkins拾遗--第五篇-git插件填坑
    Jenkins拾遗--第三篇(用户权限管理)
    Jenkins拾遗--第四篇-适当的让构建失败
    Jenkins拾遗--第二篇(初步配置Jenkins)
    Jenkins拾遗--第一篇(安装Jenkins)
    一个测试人员的2015的回顾和2016年展望
    xcode升级导致git无法使用
    在intellj idea下用sbt的坑
    本人已转战知乎,此处不玩了。
  • 原文地址:https://www.cnblogs.com/hust/p/2509709.html
Copyright © 2011-2022 走看看