current position:Home>Python notes (19): anonymous functions
Python notes (19): anonymous functions
2022-01-30 16:50:01 【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 ~
Anonymous functions
stay python in , Except for general use def Outside the defined function , There is another use lambda Defined anonymous functions . This function can be used where any ordinary function can be used , But when defined, it is strictly limited to a single expression . Semantically speaking , It's just the syntax of ordinary functions .
If we need to define a particularly simple function , for example
def add(a, b):
s = a + b
return s
Copy code
So there's a problem , So elegant Python How can such ugly code appear , Is there any way to simplify it to 1 What about line code ? So elegant Python There must be a way to simplify it ! It used to Anonymous functions 了 .
python Use in **lambda
** Keyword to create anonymous functions .
Grammar format
lambda [ Parameters 1 [, Parameters 2,.. Parameters n]]: expression
Copy code
lambda parameter list :return [ expression ] Variable
because lambda What is returned is the function object ( What is built is a function object ), So you need to define a variable to receive
The sample code is as follows :
news_add = lambda a, b: a + b
# The one above is equal to
def news_add_old(a, b):
return a + b
x = news_add_old(5, 10)
y = news_add(5, 10) # Call anonymous functions
print(x, y) # 15 15
Copy code
Use with built-in functions
list1 = [{"a": 10, "b": 20}, {"a": 20, "b": 20}, {"a": 50, "b": 20}, {"a": 6, "b": 20}, {"a": 9, "b": 20}]
# The one on that list a Maximum
max_value = max(list1, key=lambda x: x["a"])
print(max_value)
# If you write with ordinary functions, there are a few more lines
def func(di):
return di["a"]
max_value = max(list1, key=func) # You can't add it here () Otherwise, it means that
print(max_value)
Copy code
Take anonymous functions as arguments
def func(a, b, fun):
s = fun(a, b)
return s
z = func(5, 10, lambda a, b: a + b)
print(z) # 15
Copy code
lambda The process of defining functions can be omitted , Make the code simpler , And don't worry about naming , But in PEP8 It is not recommended to use in the specification lambda In this way .
copyright notice
author[A bowl week],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201301649586016.html
The sidebar is 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
guess what you like
-
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)
Random recommended
- 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
- Introduction to python (IV) dynamic web page analysis and capture
- Python practice - capture 58 rental information and store it in MySQL database
- leetcode 119. Pascal's Triangle II(python)
- leetcode 31. Next Permutation(python)
- [algorithm learning] 807 Maintain the city skyline (Java / C / C + + / Python / go / trust)
- The rich woman's best friend asked me to write her a Taobao double 11 rush purchase script in Python, which can only be arranged
- Glom module of Python data analysis module (1)
- Python crawler actual combat, requests module, python realizes the full set of skin to capture the glory of the king
- Summarize some common mistakes of novices in Python development
- Python libraries you may not know
- [Python crawler] detailed explanation of selenium from introduction to actual combat [2]
- This is what you should do to quickly create a list in Python
- On the 55th day of the journey, python opencv perspective transformation front knowledge contour coordinate points
- Python OpenCV image area contour mark, which can be used to frame various small notes
- How to set up an asgi Django application with Postgres, nginx and uvicorn on Ubuntu 20.04
- Initial Python tuple
- Introduction to Python urllib module
- Advanced Python Basics: from functions to advanced magic methods
- Python Foundation: data structure summary
- Python Basics: from variables to exception handling
- Python notes (22): time module and calendar module