This article mainly introduces how to use the map, reduce, filter, and sorted functions in Python. it is the basic knowledge of getting started with Python. For more information, see
Map
map(funcname, list)
The python map function allows the function to pass each element of the list directly to funcname as a parameter and return a new list in the response.
As follows:
Def sq (x): return x * x # evaluate the square map (sq, [, 9]) of x # [1, 9, 25, 49, 81]
It is convenient to convert each element in the list.
For example, convert each int in the list to str
map(str, [23,43,4545,324]) #['23', '43', '4545', '324']
Of course, the second parameter is list, which can be tuple or set list structure. dict cannot, but the returned result is list.
map(sq, (1,3, 5,7,9)) # tuple [1, 9, 25, 49, 81]map(sq, set([1,3, 5,3,7,9])) # set [1, 9, 81, 25, 49]
By the way, the dict structure is represented by {}, as shown in figure
{"name": "Yi_Zhi_Yu", "age":25}
Is an intuitive key-value form. if {} contains a list-like structure, for example:
{"Yi_Zhi_Yu", 25}
In fact, this is the final return form of the set, which is equivalent:
Set (["Yi_Zhi_Yu", 25]) # The final output format is {25, 'Yi _ Zhi_Yu '}
In this case, {} will remove duplicates when there are duplicates.
{1,3, 5, 3, 7, 9} #{1, 3, 5, 7, 9}
Reduce
reduce(funcname, list)
Compared with map, reduce is similar to an application method of an aggregation class. parameters in the list are passed to funcname in sequence. each funcname parameter is the execution result of the previous funcname and the element in the next list, therefore, the funcname parameter must be two. the execution process is a bit like recursion.
For example, calculate the sum of range (1,101) (excluding 101,
def c_sum(x, y): return x + y;reduce(c_sum, range(1,101)) #5050
Filter
filter(funcname, list)
The execution process passes the elements in the list to the funcname function sequentially, and the elements are retained or discarded based on the True or False returned by funcname.
For example, return all int data in a list.
def is_int(x): if isinstance(x, (int)): return True else: return False filter(is_int, ["Yi",2, "3", 4]) #[2, 4]sortedsorted( list, [comp_func])
Sorting method. The second parameter is an optional parameter. The result is sorted based on the value returned by the optional parameter. comp_func accepts two parameters (x, y), and the final returned result is-1.0, 1, if-1 is returned, x is returned. Y. Therefore, the actual sorting can be customized.
The default value is positive Order:
sorted([3,4, 12, 5, 9, 1]) #[1, 3, 4, 5, 9, 12]
If you want to arrange them in reverse order, use the following custom method:
def m_order(x, y): if(x > y): return -1 elif(x == y): return 0 else: return 1sorted([3,4, 12, 5, 9, 1], m_order) #[12, 9, 5, 4, 3, 1]