This article mainly introduces how to use lambda efficient operation List in Python. It integrates functions such as map, filter, reduce, and sorted. For more information, see
Introduction
Lambda
Python is used to support the assignment of functions to Variables. by default, an operator returns a value. Therefore, you do not need to add the return keyword. Otherwise, an error is reported.
result = lambda x: x * xresult(2) # return 4map()/filter()/reduce()
Two parameters are required. The first is a processing function, and the second is a sequence (list, tuple, dict)
Map ()
Process the elements in the sequence using the processing function and return a new list.
Filter ()
Filter the elements in the sequence using the function and return a new list.
Reduce ()
Returns a result using a binary function.
Use the above three functions with lambda
Li = [1, 2, 3, 4, 5] # Add 1map (lambda x: x + 1, li) for each element in the sequence # [2, 3, 4, 5, 6] # return the even filter (lambda x: x % 2 = 0, li) # [2, 4] # return the result of multiplying all elements reduce (lambda x, y: x * y, li) #1*2*3*4*5 = 120
Sorted () and lambda sort the list
Sorted is used to sort the list. it is more intelligent than the list that comes with two lists. each list has a dictionary ([{},{}]). it is required that the two lists be merged and sorted by time. the time in the two lists has been changed from time format to string format to json output. the field name is sort_time. now they are arranged in descending order.
Sorted usage
Sorted (iterable, cmp = None, key = None, reverse = False) --> new sorted list terable: is an iterative type; cmp: a function used for comparison, the key determines what to compare. it has a default value. it is an item in the iteration set. key: an attribute and function of the list element is used as a keyword. it has a default value. it is an item in the iteration set. reverse: sorting rules. reverse = True or reverse = False, with the default value. * Return value: it is a sorted and iteratable type, which is the same as that of iterable.
Sorted () is used together with lambda to sort the iteratable types with sort_time
sorted(data, key=lambda d: d['sort_time'], reverse=True)