为什么使用 lambda 函数?

我可以找到很多东西告诉我什么是 lambda 函数,语法是如何工作的,什么不是。但是除了“酷因子”(我可以在中间调用一个函数来调用另一个函数,太棒了!)我还没有看到一些非常有说服力的东西来说明我为什么真的需要/想要使用它们。

在我看到的大多数例子中,它似乎更多的是一种文体或结构上的选择。而且有点打破了 Python 规则中的“唯一正确的做事方式”。它如何使我的程序更正确、更可靠、更快或更容易理解?(我见过的大多数编码标准都倾向于告诉您避免在一行中使用过于复杂的语句。如果这样更容易阅读,就把它拆散。)

58066 次浏览

For me it's a matter of the expressiveness of the code. When writing code that people will have to support, that code should tell a story in as concise and easy to understand manner as possible. Sometimes the lambda expression is more complicated, other times it more directly tells what that line or block of code is doing. Use judgment when writing.

Think of it like structuring a sentence. What are the important parts (nouns and verbs vs. objects and methods, etc.) and how should they be ordered for that line or block of code to convey what it's doing intuitively.

Here's a good example:

def key(x):
return x[1]


a = [(1, 2), (3, 1), (5, 10), (11, -3)]
a.sort(key=key)

versus

a = [(1, 2), (3, 1), (5, 10), (11, -3)]
a.sort(key=lambda x: x[1])

From another angle: Lambda expressions are also known as "anonymous functions", and are very useful in certain programming paradigms, particularly functional programming, which lambda calculus provided the inspiration for.

http://en.wikipedia.org/wiki/Lambda_calculus

In some cases it is much more clear to express something simple as a lambda. Consider regular sorting vs. reverse sorting for example:

some_list = [2, 1, 3]
print sorted(some_list)
print sorted(some_list, lambda a, b: -cmp(a, b))

For the latter case writing a separate full-fledged function just to return a -cmp(a, b) would create more misunderstanding then a lambda.

The syntax is more concise in certain situations, mostly when dealing with map et al.

map(lambda x: x * 2, [1,2,3,4])

seems better to me than:

def double(x):
return x * 2


map(double, [1,2,3,4])

I think the lambda is a better choice in this situation because the def double seems almost disconnected from the map that is using it. Plus, I guess it has the added benefit that the function gets thrown away when you are done.

There is one downside to lambda which limits its usefulness in Python, in my opinion: lambdas can have only one expression (i.e., you can't have multiple lines). It just can't work in a language that forces whitespace.

Plus, whenever I use lambda I feel awesome.

Yes, you're right — it is a structural choice. It probably does not make your programs more correct by just using lambda expressions. Nor does it make them more reliable, and this has nothing to do with speed.

It is only about flexibility and the power of expression. Like list comprehension. You can do most of that defining named functions (possibly polluting namespace, but that's again purely stylistic issue).

It can aid to readability by the fact, that you do not have to define a separate named function, that someone else will have to find, read and understand that all it does is to call a method blah() on its argument.

It may be much more interesting when you use it to write functions that create and return other functions, where what exactly those functions do, depends on their arguments. This may be a very concise and readable way of parameterizing your code behaviour. You can just express more interesting ideas.

But that is still a structural choice. You can do that otherwise. But the same goes for object oriented programming ;)

One use of lambda function which I have learned, and where is not other good alternative or at least looks for me best is as default action in function parameter by

parameter=lambda x: x

This returns the value without change, but you can supply one function optionally to perform a transformation or action (like printing the answer, not only returning)

Also often it is useful to use in sorting as key:

key=lambda x: x[field]

The effect is to sort by fieldth (zero based remember) element of each item in sequence. For reversing you do not need lambda as it is clearer to use

reverse=True

Often it is almost as easy to do new real function and use that instead of lambda. If people has studied much Lisp or other functional programming, they also have natural tendency to use lambda function as in Lisp the function definitions are handled by lambda calculus.

Lambda functions are most useful in things like callback functions, or places in which you need a throwaway function. JAB's example is perfect - It would be better accompanied by the keyword argument key, but it still provides useful information.

When

def key(x):
return x[1]

appears 300 lines away from

[(1,2), (3,1), (5,10), (11,-3)].sort(key)

what does key do? There's really no indication. You might have some sort of guess, especially if you're familiar with the function, but usually it requires going back to look. OTOH,

[(1,2), (3,1), (5,10), (11,-3)].sort(lambda x: x[1])

tells you a lot more.

  1. Sort takes a function as an argument
  2. That function takes 1 parameter (and "returns" a result)
  3. I'm trying to sort this list by the 2nd value of each of the elements of the list
  4. (If the list were a variable so you couldn't see the values) this logic expects the list to have at least 2 elements in it.

There's probably some more information, but already that's a tremendous amount that you get just by using an anonymous lambda function instead of a named function.

Plus it doesn't pollute your namespace ;)

Lambdas allow you to create functions on the fly. Most of the examples I've seen don't do much more than create a function with parameters passed at the time of creation rather than execution. Or they simplify the code by not requiring a formal declaration of the function ahead of use.

A more interesting use would be to dynamically construct a python function to evaluate a mathematical expression that isn't known until run time (user input). Once created, that function can be called repeatedly with different arguments to evaluate the expression (say you wanted to plot it). That may even be a poor example given eval(). This type of use is where the "real" power is - in dynamically creating more complex code, rather than the simple examples you often see which are not much more than nice (source) code size reductions.

Ignore for a moment the detail that it's specifically anonymous functions we're talking about. functions, including anonymous ones, are assignable quantities (almost, but not really, values) in Python. an expression like

map(lambda y: y * -1, range(0, 10))

explicitly mentions four anonymous quantities: -1, 0, 10 and the result of the lambda operator, plus the implied result of the map call. it's possible to create values of anonymous types in some languages. so ignore the superficial difference between functions and numbers. the question when to use an anonymous function as opposed to a named one is similar to a question of when to put a naked number literal in the code and when to declare a TIMES_I_WISHED_I_HAD_A_PONY or BUFFER_SIZE beforehand. there are times when it's appropriate to use a (numeric, string or function) literal, and there are times when it's more appropriate to name such a thing and refer to it through its name.

see eg. Allen Holub's provocative, thought-or-anger-provoking book on Design Patterns in Java; he uses anonymous classes quite a bit.

Lambda, while useful in certain situations, has a large potential for abuse. lambda's almost always make code more difficult to read. And while it might feel satisfying to fit all your code onto a single line, it will suck for the next person who has to read your code.

Direct from PEP8

"One of Guido's key insights is that code is read much more often than it is written."

Lambdas are objects, not methods, and they cannot be invoked in the same way that methods are. for e.g

succ = ->(x){ x+1 }

succ mow holds a Proc object, which we can use like any other:

succ.call(2)

gives us an output = 3

I want to point out one situation other than list-processing where the lambda functions seems the best choice:

from tkinter import *
from tkinter import ttk
def callback(arg):
print(arg)
pass
root = Tk()
ttk.Button(root, text = 'Button1', command = lambda: callback('Button 1 clicked')).pack()
root.mainloop()

And if we drop lambda function here, the callback may only execute the callback once.

ttk.Button(root, text = 'Button1', command = callback('Button1 clicked')).pack()

Another point is that python does not have switch statements. Combining lambdas with dicts can be an effective alternative. e.g.:

switch = {
'1': lambda x: x+1,
'2': lambda x: x+2,
'3': lambda x: x+3
}


x = starting_val
ans = expression
new_ans = switch[ans](x)

Lambdas are anonymous functions (function with no name) that can be assigned to a variable or that can be passed as an argument to another function. The usefulness of lambda will be realized when you need a small piece of function that will be run once in a while or just once. Instead of writing the function in global scope or including it as part of your main program you can toss around few lines of code when needed to a variable or another function. Also when you pass the function as an argument to another function during the function call you can change the argument (the anonymous function) making the function itself dynamic. Suppose if the anonymous function uses variables outside its scope it is called closure. This is useful in callback functions.

It is definitely true that abusing lambda functions often leads to bad and hard-to-read code. On the other hand, when used accurately, it does the opposite. There are already great answers in this thread, but one example I have come across is:

def power(n):
return lambda x: x**n


square = power(2)
cubic = power(3)
quadruple = power(4)


print(square(10)) # 100
print(cubic(10)) # 1000
print(quadruple(10)) # 10000

This simplified case could be rewritten in many other ways without the use of lambda. Still, one can infer how lambda functions can increase readability and code reuse in perhaps more complex cases and functions with this example.

you master lambda, you master shortcuts in python.Here is why:

data=[(lambda x:x.text)(x.extract())  for x in soup.findAll('p') ]
^1           ^2         ^3           ^4

here we can see 4 parts of the list comprehension:

  • 1: i finally want this
  • 2: x.extract will perform some operation on x, here it pop the element from soup
  • 3: x is the list iterable which is passed to the input of lambda at 2 along with extract operation
  • 4: some arbitary list

i had found no other way to use 2 statements in lambda, but with this kind of pipe-lining we can exploit the infinite potential of lambda.

Edit: as pointed out in the comments, by juanpa, its completely fine to use x.extract().text but the point was explaining the use of lambda pipe, ie passing the output of lambda1 as input to lambda2. via (lambda1 y:g(x))(lambda2 x:f(x))