current position:Home>Python notes (20): built in high-order functions

Python notes (20): built in high-order functions

2022-01-30 15:38:53 A bowl week

Little knowledge , Great challenge ! This article is participating in “ A programmer must have a little knowledge ” Creative activities .

Hello everyone , I am a A bowl week , One doesn't want to be drunk ( Internal volume ) The front end of the . If you are lucky enough to get your favor , I'm very lucky ~

Python Built in higher-order functions

map()

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

Grammar format

map(function, iterable, ...)
 Copy code 

The first parameter function Call... With each element in the parameter sequence function function ,

The second parameter iterable One or more sequences

Return contain every time function The function returns a new list of values .

Sample code

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


#  Generate a function 
def func(lt):  #  Return even number , Odd number +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]
 Copy code 

reduce() function

reduce() Function in Python2x It is the built-in function of the system , To Python3x Has been included in functools It's in the library

reduce() The function accumulates elements in a sequence of parameters .

Function to set a data set ( Linked list , Tuples etc. ) Do the following for all data in : Pass it on to reduce The function in function( There are two parameters ) Let's start with the... In the set 1、2 Elements to operate , The results are then used with the third data function Function operation , Finally, we get a result .

Grammar format

reduce(function, iterable[, initializer])
 Copy code 

function -- function , There are two parameters

iterable -- Iteratable object

initializer -- Optional , Initial parameter

Return the result of function calculation .

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
 Copy code 

The calculation results will be stored in x, Accumulated every time .initializer Is set x The initial value of the

filter() function

filter() Function to filter the sequence , Filter out the elements that do not meet the conditions , Returns an iterator object , If you want to convert to a list , have access to list() To convert .

This accepts two parameters , The first one is a function , The second is the sequence , Each element of the sequence is passed as a parameter to the function for judgment , Then return True or False, And then it will return True Is placed in the new list .

Grammatical structure

filter(function, iterable)
 Copy code 

function -- Judgment function .

iterable -- Iteratable object .

Returns an iteratable object

sorted() function

sorted() Function to sort all objects that can be iterated , It's a new list.

Grammatical structure

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

iterable -- Iteratable object .

cmp -- The function of comparison , This has two parameters , The values of the parameters are taken from the iteratable objects , The rule that this function must follow is , Greater than returns 1, Less than returns -1, Is equal to returns 0.

key -- It's basically a comparison element , There is only one parameter , The parameters of the specific function are taken from the iterable object , Specifies an element in an iterable object to sort .

reverse -- Sort rule ,reverse = True Descending , reverse = False Ascending ( Default ).

Return to the 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 all people older than 18 Year old student 
result = filter(lambda x: x['age'] > 18, students)
print(list(result))  # [{'name': 'tom', 'age': 20}, {'name': 'mark', 'age': 21}]

#  Sort by age 
students = sorted(students, key=lambda x: x['age'], reverse=True)  #  utilize 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}]
'''
 Copy code 

copyright notice
author[A bowl week],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201301538507275.html

Random recommended