Several higher-order functions built into Python
Everything can be an object in Python; The meaning of high-order function is that its incoming parameters include function object, and the function that receives function object as parameter is high-order function. There are several built-in higher-order functions in Python, including map(),sorted(), and filtered (); Earlier versions of Python also had built-in reduce (), which is now housed in the FuncTools module.
The map () function
In the previous article has talked in detail, for details refer to https://blog.csdn.net/Always_…
A supplementary point:
For most scenarios where map() is used, a simple list derivation can be used instead. For cases where multiple parameters are passed in, it is generally necessary to convert to the subscript form:
> > > a = [1, 2, 3] > > > b = [10, 30] > > > [[I] a [I] + b for I in range (3)] [11, 22, 33]
Sorted () function
If we mention sorted(), we must distinguish them from sort() :
- The sorted() function is a built-in function that takes an iterable object, sorts all iterable objects according to certain rules, and returns a new iterable object.
- The sort() function is a method on the List object that directly modifies the original List to return None
> > > a =,3,1 [2] > > > b = sorted # (a) returns a new object > > > b [1, 2, 3] > > > # original object does not change [2, 3, 1) > > > a =,3,1 [2] > > > b = a.s ort # () returns None > > > a [1, 2, Sort (n): sort(n): sort(n): sort(n): sort(n): sort(n): sort(n): sort(n): sort(n): sort(n): sort(n): sort(n): sort(n): sort(n): sort(n); File "<input>", line 1, in <module> NameError: name 'sort' is not defined
And the sorted() function itself is useful, especially in conjunction with keys. The reason why sorted is a higher-order function is that its internal arguments can accept a function object.
> > > a = [1, 2, 3, 1, 10, 20] > > > sorted (a) # default from small to big [- 20-2, 1, 1, 3, 10] > > > sorted (a, reverse = True) # from big to small [10, 3, 1, 1, 2, -20] >>sorted(a,key=lambda x:x**2)#key Passed in a function object that sorted the numbers by the square [1, -1, -2, 3, 10, -20]
For sorting multidimensional lists:
,3,1 > > > a = [[2], [10, 1, 3], [1,20,2]] > > > sorted (a, key = lambda x: x [1]) # according to the number of each row 2 sort [[10, 1, 3], [2, 3, 1], [- 1, 20, 2]]
For string sorting:
>>>a=['hacca','de','djnhg']
>>>sorted(a,key=lambda x:x[-1])
['hacca', 'de', 'djnhg']
For custom object sorting:
class A: def __init__(self,a,b): self.a=a self.b=b def __repr__(self): S_ s_ return '% % % s' % (self. The magic __class__. __name__, self. A, the self. B) > > > x = (a (1, 2), a (1, 3), a (10, 1)] > > > sorted (x, key = lambda x: x.a) [A_-10_1, A_-1_3, A_1_2]
In general, sorted() works nicely with key using lambda anonymous functions.
The filter () function
Filter () is, as the name implies, a filter function; Take a function and an iterable object, and apply the function to the iterable object in turn. The function must return either True or False each time. Finally, we keep the elements that return True.
> > > a = [1, 2, 3, 4, 5] > > > def func (x) : >>> return x%2==0 >>>list(filter(func,a))# 2 4] > > > [x in [1, 2, 3, 4, 5] if x % for x 2 = = 0] # list can also be used to implement type (2, 4)
Let’s take a relatively complicated example. How to identify whether students are biased subjects? Students who meet one of the following criteria will be considered partial subjects:
- Two subjects scored above 80 points and one subject scored below 60 points.
- One of them got more than 90 points, and the other two got less than 60 points.
- One subject was above 90 points, but the average score of the three subjects was below 70 points.
scores = [ ("Emma", 89 , 90 , 59), ("Edith", 99 , 49 , 59), ("Sophia", 99 , 60 , 20), ("May", 40 , 94 , 59), ("Ashley", 89 , 90 , 59), ("Arny", 89 , 90, 69), ("Lucy", 79 , 90 , 59 ), ("Gloria", 85 , 90 , 59), ("Abby", 89 , 91 , 90)] def handle_filter(a): s = sorted(a[1: If s[-2] > 80 and s[0] < 60; if s[-2] > 80 and s[0] < 60: If s[-1] > 90 and s[1] < 60; if s[-1] > 90 and s[1] < 60: return True if s[-2] > 80 and sum(s)/len(s) < 60: # 1 subject with a score above 90; Return True return False >>>list(filter(handle_filter, scores)) [('Emma', 89, 90, 59), ('Edith', 99, 49, 59), ('May', 40, 94, 59), ('Ashley', 89, 90, 59), ('Gloria', 85, 90, 59)]
As you can see, for such a filter with complex rules, the list derivation will be very troublesome and the code readability will be poor. At this time, it is better to use filter. But it’s better than a for loop.
To reduce () function
Reduce in Python 3 is already in the FuncTools module, and the syntax is as follows:
reduce(function, sequence[, initial]) -> value
The reduce function takes a function and a sequence and returns a single value, evaluated as follows: 1. 2. Function is called and result is passed in from the previous step to the next item from the sequence. Function is called and result is returned. This operation is repeated until the sequence has been iterated and the final result is returned. Note that when initial is specified, the two parameters passed in step1 are the first items of the initial and sequence, respectively. Reduce () can accept at most three parameters, func, sequence, and initial.
> > > the reduce (lambda a, b, a + b, [1, 2, 3, 4, 5]) first value of 1 # incoming 15 > > > the reduce (lambda a, b, a + b, [1, 2, 3, 4, 5], 100) # incoming first initial value is 100 115
The reduce function can be replaced by sum.