https://qiita.com/ganariya/items/fb3f38c2f4a35d1ee2e8
In order to study Python, I copied a swarm intelligence library called acopy.
In acopy, many interesting Python grammars and idioms are used, and it is summarized that it is convenient among them.
This time, you'll learn about Python lambda expressions.
Lambda expression is a concept used in many other programming languages and means ** anonymous function **. It is not necessary to give a name, ** when the scope to be used is very small **, the lambda expression is to define an anonymous function on the spot and throw it away **.
In C ++, it can be used with the notation []() {}
.
The lambda expression is expressed in the form of lambda argument: processing
.
The feature is that a value is always returned as a result of processing.
For example, let's create an add function that adds the arguments of two integers, and an lm_add function that expresses it as lambda.
def add(x, y):
return x + y
lm_add = lambda x, y: x + y
x = 10
y = 40
'''
50
50
'''
print(add(x, y))
print(lm_add(x, y))
The lm_add function behaves the same as the add function. After receiving the arguments $ x and y $ and calculating $ x + y $, it is forcibly returned.
You can use variadic arguments just like regular functions.
f = lambda *args, **kwargs: print(args, kwargs)
'''
(10, 'a') {'hello': 'world'}
'''
f(10, 'a', hello='world')
lambda expressions are basically disposable and don't need to be named, and are only used (and should be) in the smallest scopes.
For example
--As a sorting standard --As a standard for maximum value
It is often used in combination with built-in functions such as. Especially used in competitive programming.
For example, the following sorts an array of tuples in ascending order relative to the $ 1 $ element, and if they are the same, further sorts them in ascending order by the $ 0 $ element.
tuples = [(10, -3), (4, 10), (-4, 13), (-20, -50), (-20, 1), (0, 0), (-22, -50)]
tuples = sorted(tuples, key=lambda x: (x[1], x[0]))
'''
[(-20, -50), (-22, -50), (10, -3), (0, 0), (-20, 1), (4, 10), (-4, 13)]
'''
print(tuples)
Since it is not necessary to define the above comparison function outside the scope, and because the position of the function becomes far away and the burden of following the process is reduced, it seems better to define it with lambda.
I looked at lambda. Especially when doing competitive programming in Python. I would like to utilize lambda expressions in other languages as well.
Sorting that replaces $ 2 $ elements in Python (C ++ sorting, etc.) Is there no choice but to define ʻeq, lt` in the class ... (I hope it can be done with lambda)
-Python lambda is easy to understand
Recommended Posts