程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[Python] lambda expression

編輯:Python

Bowen author wangzirui32
Like can give the thumbs-up Collection Pay attention to ~~
My number 163 An original work
This article was first published in CSDN, Reprint is prohibited without permission


hello, Hello everyone , I am a wangzirui32, Today we are going to study Python in Lambda expression , Start learning !

1. What is? Lambda

Lambda stay Python The frequency used in programming is very high , This expression is actually Python The form of a special definition function in , Use it to define an anonymous function . When you need a simple function ,Lambda Can meet most of the needs .

2. Lambda grammar

Lambda The syntax is as follows :

lambda Parameters 1, Parameters 2, ...., Parameters n: Execute statement

Sample code :

# Calculation x The third power of 
f = lambda x: x**3
print(f(3))

Output :

27

Be careful ,lambda In the sentence , The colon (:) Then execute an expression , Don't need to use return Return results , You can use if sentence :

# Judge whether it is even Is an even number that returns True Otherwise return to False
f = lambda x: True if x % 2 == 0 else False
print(f(10))
print(f(11))

Output :

True
False

You can also specify multiple parameters :

# seek x y z Average value 
f = lambda x, y, z: (x+y+z)/3
print(f(11, 45, 14))

Output :

23.33333333333

3. Lambda High-order usage

3.1 Sort

The following list is available :

students = [{
"name": "John", "age": 10, "score": 87},
{
"name": "Sally", "age": 9, "score": 100},
{
"name": "James", "age": 13, "score": 95}]

demand : Sort the student information in the list by age and score .
We can use lambda Expressions and sorting functions achieve the requirements , Code :

students = [{
"name": "John", "age": 10, "score": 87},
{
"name": "Sally", "age": 18, "score": 100},
{
"name": "James", "age": 13, "score": 95}]
# there lambda Return the student's age as the sorting basis 
students.sort(key=lambda student: student['age'])
print(" Sort by age :", students)
# there lambda Returns the student's score as the sorting basis 
students.sort(key=lambda student: student['score'], reverse=True)
print(" Sort by score :", students)

Output results :

 Sort by age : [{
'name': 'John', 'age': 10, 'score': 87}, ......]
Sort by score : [{
'name': 'Sally', 'age': 18, 'score': 100}, ......]

3.2 Sequence mapping

The following list is available :

numbers = [1, 2, 3, 4, 5, 6, 7]

demand : Perform a cubic operation on all numeric elements in the list .
We can combine map Function to achieve the requirements , Code :

numbers = [1, 2, 3, 4, 5, 6, 7]
# there lamdba return x The cube of 
new_numbers = list(map(lambda x: x**3, numbers))
print(new_numbers)

Output :

[1, 8, 27, 64, 125, 216, 343]

map Functions can be used to map sequences , The call parameters are as follows :

map( Mapping function , Sequence list )

The mapping process is similar to :

numbers1234567 mapping new_numbers182764125216343

3.3 Filter element

The following list is available :

numbers = [11, 4, 5, 14, 10, 32, 50, 19, 20]

demand : Filter out of list 10 Even numbers above .
We can use filter Built in functions , Code :

numbers = [11, 4, 5, 14, 10, 32, 50, 19, 20]
new_numbers = list(filter(lambda x: x % 2 == 0 and x >= 10, numbers))
print(new_numbers)

Output :

[14, 10, 32, 50, 20]

In this lambda In the expression , We set the conditions x % 2 == 0 and x >= 10, If 2 All conditions are met , The expression result is True, Otherwise False.
The whole process is similar to :

numbers1145141032501920 Whether the conditions are met FalseFalseFalseTrueTrueTrueTrueFalseTruenew_numbersNoneNoneNone14103250None20

3.4 Specify the binding conditions of adjacent elements

The following list is available :

students = ["John", "Jack", "James", "Malfoy", "Sally"]

demand : Add... Between the names of every two students "," Connect and output .
We can use reduce function , Code :

from functools import reduce
students = ["John", "Jack", "James", "Malfoy", "Sally"]
print(reduce(lambda a, b: "{} , {}".format(a, b), students))

Output :

John , Jack , James , Malfoy , Sally

3.5 Function decorator

When a function returns lambda Anonymous functions , This is similar to Python Function decorator in , Sample code :

def welcome_text(text):
return lambda username: "Welcome {}!\n{}".format(username, text)
welcome_user = welcome_text(" Here is wangzirui32 Programming class for !")
print(welcome_user("Malfoy"))

Output :

Welcome Malfoy!
Here is wangzirui32 Programming class for !

Okay , That's all for today's lesson , I am a wangzirui32, You can collect and pay attention to what you like , See you next time !


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved