Python Built in Higher Order Function Details

  • 2021-12-12 05:01:02
  • OfStack

Directory 1, Built-in Higher Order Functions for Python 1.1 map () 1.2 reduce () Functions 1.3 reduce () Functions 1.4 sorted () Functions

1. Built-in higher-order functions of Python

1.1 map()

map() The specified sequence is mapped according to the provided function

Syntax format:

map(function, iterable, ...)

The first parameter function The function function is called with every 1 element in the parameter sequence,

The second parameter iterable 1 or more sequences

Returns every time that contains function A new list of values returned by the function.

Sample code:


list1 = [1, 2, 4, 5, 56, 12, 5, 2, 34]


#  Generate 1 Functions 
def func(lt):  #  Returns even numbers, odd numbers +1 Return 
    if lt % 2 == 0:
        return lt
    else:
        return lt + 1


list2 = map(func, list1)  #  Never add ()
#  Use lambda Keyword 
list3 = map(lambda i: i if i % 2 == 0 else i + 1, list1)
print(list(list3))  # [2, 2, 4, 6, 56, 12, 6, 2, 34]
print(list(list2))  # [2, 2, 4, 6, 56, 12, 6, 2, 34]

1.2 reduce () Function

reduce() Function in Python2x Is a built-in function of the system, to Python3x Has been classified into functools It's in the library

reduce() The function accumulates the elements in the parameter sequence.

Function to perform the following operations on all data in a data set (linked list, tuple, etc.) map(function, iterable, ...)0 The function function (with two parameters) in the set first operates on the first and second elements, and the result is then used with the third data function Function operation, and finally get a result.

Grammatical format

reduce(function, iterable[, initializer])

function --function with two arguments

iterable --Iterable objects

initializer --Optional, initial parameters

Returns the result of a function evaluation.

Sample code:


from functools import reduce

list1 = [1, 2, 3, 4, 5, 6, 7]
value = reduce(lambda x, y: x + y, list1)
print(value)  # 28 = 1+2+3+4+5+6+7

The calculation results are stored in x and accumulated each time. initializer Is to set the initial value of x

1.3 reduce () Function

filter() The list () function is used to filter the sequence, filter out the elements that do not meet the requirements, and return 1 iterator object. If you want to convert it to a list, you can use list () to convert it.

It receives two parameters, the first is a function and the second is a sequence. Each element of the sequence is passed as a parameter to the function for judgment, and then returns True or False, and finally returns True To the new list.

Grammatical structure:

filter(function, iterable)

function --Judgment function.

iterable --Iterable objects.

Returns 1 iterable object

1.4 sorted () Function

sorted() The list function sorts all iterable objects and returns a new list.

Grammatical structure:

sorted(iterable, cmp=None, key=None, reverse=False)

iterable --Iterable objects.

cmp The function of comparison, which has two parameters, the values of which are taken from the iterable object. The rule that this function must abide by is that if it is greater than, it will return 1, if it is less than-1, and if it is equal to, it will return 0.

key -is mainly used for comparison of elements, only one parameter, the specific function parameters are taken from the iterable object, the iterable object specified in one element to sort.

reverse --Collation rules, reverse = True In descending order, reverse = False Ascending (default).

Returns a reordered list.

Sample code:


students = [
    {'name': 'tom', 'age': 20},
    {'name': 'lucy', 'age': 15},
    {'name': 'lily', 'age': 13},
    {'name': 'mark', 'age': 21},
    {'name': 'jack', 'age': 13},
    {'name': 'steven', 'age': 18},
]

 
#  Find out all the people who are older than 18 Students aged 
result = filter(lambda x: x['age'] > 18, students)
print(list(result))  # [{'name': 'tom', 'age': 20}, {'name': 'mark', 'age': 21}]

#  Sorted by age from small to large 
students = sorted(students, key=lambda x: x['age'], reverse=True)  #  Utilization key

print(students)
'''
[{'name': 'mark', 'age': 21}, {'name': 'tom', 'age': 20}, 
{'name': 'steven', 'age': 18}, {'name': 'lucy', 'age': 15}, 
{'name': 'lily', 'age': 13}, {'name': 'jack', 'age': 13}]
'''

Related articles: