11.3.2.1 write code in a programming language using lambda functions Python. Lambda function. map(), filter() functions.Lambda function 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. Benefits of using Lambda expressions - lambda expressions are convenient for creating functions that have small sizes; Unnamed (anonymous) functions can be created with a statement: lambda <arguments>: <expression> For example, the next function
can be written as:
Example
map() function 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>) Examples 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() function 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>) Examples 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.
Questions:
Exercises: Ex. 1 Lambda functions Tasks:
| |
| |
Просмотров: 7267 | | |
Всего комментариев: 0 | |