Tutorial on using lambda efficient operation list in Python, pythonlambda
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)