18.104.22.168 write code in a programming language using lambda functions
Python. Lambda function. map(), filter() functions.
Often, we want to use a very simple function as an argument for higher-order functions. Moreover, such a function is often needed in the program only in one place, so it does not even need to have a name.
The Lambda operator can be used to create anonymous functions. They do not need to be isolated as a separate function and can be used as an argument to another function.
Unnamed (anonymous) functions can be created with a statement:
lambda <arguments>: <expression>
For example, the next function
can be written as:
The map() function returns a map object (which is an iterator) of the results after applying the given function to each element of the given iteration (list, tuple, etc.)
The map function can be written using the following statement:
map(<function>, <iterable object>)
Task. The map function can be used when entering two numbers on the same line. Each string that we get in the list with the help will be converted to an integer.
We can use the next code:
Or change for the next code using the map function:
If we want to increase each number from the range from 5 to 10 by 2, then we use the map function and pack the resulting values into a list.
Filter() is a built-in Python function. You can apply a filter function to an iterable, such as a list or dictionary, and create a new iterator. This new iterator can filter out specific elements very efficiently based on the condition you provide.
The filter function can be written using the following statement:
filter(<function>, <iterable object>)
Task. Print all integers from 10 to 50 that are divisible by 10.
Task. Using the filter function, remove from the list only those words whose length is greater than five
Task. Print the squares of all integers between 0 and 20 that are divisible by 3.
Ex. 1 Lambda functions
|Просмотров: 381 | ||
|Всего комментариев: 0|