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
The sidebar is recommended
- Python code reading (Part 44): find the location of qualified elements
- Elegant implementation of Django model field encryption
- 40 Python entry applet
- Pandas comprehensive application
- Chapter 2: Fundamentals of python-3 character string
- Python pyplot draws a parallel histogram, and the x-axis value is displayed in the center of the two histograms
- [Python crawler] detailed explanation of selenium from introduction to actual combat [1]
- Curl to Python self use version
- Python visualization - 3D drawing solutions pyecharts, Matplotlib, openpyxl
- Use python, opencv's meanshift and CAMSHIFT algorithms to find and track objects in video
guess what you like
-
Using python, opencv obtains and changes pixels, modifies image channels, and trims ROI
-
[Python data collection] university ranking data collection
-
[Python data collection] stock information collection
-
Python game development, pyGame module, python takes you to realize a magic tower game from scratch (2)
-
Python solves the problem of suspending execution after clicking the mouse in CMD window (fast editing mode is prohibited)
-
[Python from introduction to mastery] (II) how to run Python? What are the good development tools (pycharm)
-
Python type hints from introduction to practice
-
Python notes (IX): basic operation of dictionary
-
Python notes (8): basic operations of collections
-
Python notes (VII): definition and use of tuples
Random recommended
- Python notes (6): definition and use of lists
- Python notes (V): string operation
- Python notes (IV): use of functions and modules
- Python notes (3): conditional statements and circular statements
- Python notes (II): lexical structure
- Notes on python (I): getting to know Python
- [Python data structure series] - tree and binary tree - basic knowledge - knowledge point explanation + code implementation
- [Python daily homework] Day7: how to combine two dictionaries in an expression?
- How to implement a custom list or dictionary in Python
- 15 advanced Python tips for experienced programmers
- Python string method tutorial - how to use the find() and replace() functions on Python strings
- Python computer network basics
- Python crawler series: crawling global airport information
- Python crawler series: crawling global port information
- How to calculate unique values using pandas groupby
- Application of built-in distribution of Monte Carlo simulation SciPy with Python
- Gradient lifting method and its implementation in Python
- Pandas: how to group and calculate by index
- Can you create an empty pandas data frame and fill it in?
- Python basic exercises teaching! can't? (practice makes perfect)
- Exploratory data analysis (EDA) in Python using SQL and Seaborn (SNS).
- Turn audio into shareable video with Python and ffmpeg
- Using rbind in python (equivalent to R)
- Pandas: how to create an empty data frame with column names
- Talk about quantifying investment using Python
- Python, image restoration in opencv - CV2 inpaint
- Python notes (14): advanced technologies such as object-oriented programming
- Python notes (13): operations such as object-oriented programming
- Python notes (12): inheritance such as object-oriented programming
- Chapter 2: Fundamentals of python-5 Boolean
- Python notes (11): encapsulation such as object-oriented programming
- Python notes (10): concepts such as object-oriented programming
- Gradient lifting method and its implementation in Python
- Van * Python | simple crawling of a site course
- Chapter 1 preliminary knowledge of pandas (list derivation and conditional assignment, anonymous function and map method, zip object and enumerate method, NP basis)
- Nanny tutorial! Build VIM into an IDE (Python)
- Fourier transform of Python OpenCV image processing, lesson 52
- Introduction to python (III) network request and analysis
- China Merchants Bank credit card number recognition project (Part I), python OpenCV image processing journey, Part 53
- Python practice - capture 58 rental information and store it in MySQL database