+ 1
What are lambdas? I get some of it, but...
I know that lambdas are able to go into arguments, but what do they mean? Is it like def hi: (lambda: x*2) So would lambda be x times 2 for that line of code? So if I did x = 2 print hi would that print 4?
3 ответов
+ 5
lambda x: x**2 + 2*x - 5
Those things are actually quite useful. Python supports a style of programming called functional programming where you can pass functions to other functions to do stuff. Example:
mult3 = filter(lambda x: x % 3 == 0, [1, 2, 3, 4, 5, 6, 7, 8, 9])
sets mult3 to [3, 6, 9], those elements of the original list that are multiples of 3. This is shorter (and, one could argue, clearer) than
def filterfunc(x): return x % 3 == 0 mult3 = filter(filterfunc, [1, 2, 3, 4, 5, 6, 7, 8, 9])
Of course, in this particular case, you could do the same thing as a list comprehension:
mult3 = [x for x in [1, 2, 3, 4, 5, 6, 7, 8, 9] if x % 3 == 0]
(or even as range(3,10,3)), but there are many other, more sophisticated use cases where you can't use a list comprehension and a lambda function may be the shortest way to write something out.
+ 6
lambdas are just anonymous inline functions.
For example,
def fun(x):pass
The function has a name "fun"
lambda x: pass
The function has no name, but
fun= lambda x: pass
The function gets a name.
0
Ok thanks =)