为什么使用Lambda而不是一行函数声明?

10

前几天我写了一个类似于以下lambda表达式:

fetch = lambda x: myDictionaryVariable.get(x, "")

但现在我刚学到,你可以使用分号;代替换行符来分隔Python语句,而且学到了即使使用冒号,也可以在一行上编写简单的语句。因此,我意识到我还可以写成这样:

def fetch(x): return myDictionaryVariable.get(x, "")

虽然我在这里没有使用;,但如果有需要,我可以使用它,从而为我的一行函数提供更多功能。我可以这样写:

Not that I'm using the ; here, but if I needed to I could, and thusly provide even more functionality for my 1-line function. I could write:

def strangeFetch(x): y = "unicorn"; return menu.get(x, y)

那么我为什么需要lambda?它们为什么是Python的一部分?在这种情况下,它们添加了什么?


10
不要担心-每当有人询问lambda时,关闭投票很快就会跟随。 我怀疑他们是Lisp'ers,他们害怕读到关于lambda的不好的事情;-) 顺便说一下,不要迷恋1行代码:代码被阅读的频率比编写的频率更高,并且strangeFetch()很糟糕。 - Tim Peters
2
每当有人问“为什么语言X设计成这样?”时,这种情况也会发生。 - Barmar
Barmar,我确实看过那篇文章,但我认为我的问题不同之处在于,我是特别询问何时使用它们而不是使用一行def语句。哦,嘿@TimPeters,我也想知道您对我刚刚提出的这个问题的最佳实践有什么官方见解:https://dev59.com/0nrZa4cB1Zd3GeqP23kY - temporary_user_name
@Barmar,我曾经成功地重新打开过其中一个!令人惊讶的是,设计决策往往有其原因。当然,同样令人惊讶的是,有时候也没有原因;-) - Tim Peters
2
并不是说设计决策没有理由,而是因为讨论这些理由被认为不符合 SO 的主题。 - Barmar
显示剩余2条评论
3个回答

10
  1. Lambda functions don't need a name. They don't clog your namespace just for a function which is used only once.

    a = [[1], [1, 2], [1, 2, 3]]
    print min(a, key = lambda x:len(x))
    print locals()
    

    As you can see, though we created a lambda function (in this case, we could have directly used len), it does not add up to the local namespace.

  2. They are use and throw type functions. They could be GCed after the line in which they are used, unless they are assigned to some variables.

  3. They don't allow any python statements and assignments, so they can be little trusted with side-effects.

    l = [1, 2]
    lambda: l = []
    

    This will throw an error, SyntaxError: can't assign to lambda. (You can mutate mutable objects though).

  4. Sometimes, they can be used to beat the effect of closures.


6

lambda 在你想要将匿名函数作为另一个函数的参数时非常有用。如果它只在那一个地方使用,那么就不需要给它分配一个名称。

可以将 lambda 分配给变量的能力仅仅是语言正交性的副产品:变量可以持有任何类型的值,而由 lambda 创建的函数只是一个值。


4

lambda表达式本身就是一个值,而def语句不是。这是因为def语句本质上是一个函数文字加上一个赋值语句,在Python中赋值不是一个表达式。

但你并不需要lambda表达式。你可以用命名函数完成所有lambda表达式能做的事情。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接