Studying the python , I came across lambda -functions. But nowhere I have not found an example of where they are really - only elementary examples of the species printa (lambda x, y: x ** 2 + y ** 2) , where it is quite possible to remove the functional wrapper. Why are they really needed and useful?
question@mail.ru
·
01.01.1970 03:00
Why do you need Lambda functions?
answer@mail.ru
·
01.01.1970 03:00
They cannot be 100% , that is, it is impossible to write a program without workings, without lambda -function - it is possible, but it is shorter and more convenient with them. For example, you need to print a dictionary in decreasing order of each value:
Bigrams = {: [ 10 , 11 , 12 ], : [ 5 , - 5 , 8 ], : [ 105 , 1 , 0 ], : [ 6 , 6 ], " "EF" ": [ 15 , 20 , 15 ], : [ 22 , 11 , 32 ], : [ 20 , 20 , 20 ]} sorter = sorted (bigrams, key = lambda key: sum (bigrams [key]), reverse = true ) for key in sorter: print (key, bigrams [key]) otherwise you need to write a function:
from functools import partial def sort_func ( key, dict ): retu sum ( dict [key]) bigrams = {: [ 10 , 11 , 12 ], : [ 5 , - 5 , 8 ], "" cd "" : [ 105 , 1 , 0 ], "de" ": [ 6 , 6 ], : [ 15 , 20 , 15 ], : [ 22 , 11 , 32 ], "gh" ": [ 20 , 20 , 20 ]} partial_Sort = PARTIAL (SORT_FUNC, dict = Bigrams) sorter = sorted (bigrams.keys (), key = partial_sort, reverse = true ) for key in sorter: print (key, bigrams [key]) the result is the same, but not with the lambda, not You need to look for the eyes of sort_FUNC - it is immediately clear how exactly the collection is sorted. The standard library is full of functions that take other functions: map , reduce
, filter , sorted , a man , all you can write a closure:
DeF access ( x ): retu lambda y: x + yead_to_ten = Addition ( 10 ) print (add_to_ten ( 8 )) print (ad_to_ten ( 6 )) in theory, the Lambda function is absolutely the same as ordinary functions, but without a name:
Class = "" Data-Highlighted = ""> def funch ( x ): func = lambda x: x + 1 retu 100 import DIS print (Dis.dis (FUNC))
PRE> shows that a new function is really created, without fraud.
Blogs
How to send an HTTP request with requests
Mathematical operations in Python: addition, division, remainder, roots and degrees
Common bugs in Python and how to fix them: A complete guide for beginners and more
Functions in Python: announcement, arguments, value returns and global variables