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

The king of all lambda function in Python

編輯:Python

Python Provides a lot of libraries and built-in functions . There are different ways to perform the same task , And in the Python in , There is a universal function :lambda function , It can be used anywhere in different ways .

Today, I will study this function with you , Like, remember to like 、 Collection 、 Focus on .

At the end of the technical exchange document

Lambda Function introduction

Lambda Functions are also called anonymous ( There is no name ) function , It directly accepts the number of parameters and the conditions or operations to be performed with that parameter , The parameters are separated by colons , And return the final result . To perform a small task when writing code on a large code base , Or perform a small task in a function , It is used in the normal process lambda function .

lambda argument_list:expersion

argument_list It's a list of parameters , Its structure and Python Middle function (function) The parameter list is the same

a,b
a=1,b=2
*args
**kwargs
a,b=1,*args
empty
....

expression Is an expression about parameters , The parameters appearing in the expression need to be in argument_list There are definitions. , And the expression can only be single line .

1
None
a+b
sum(a)
1 if a >10 else 0
[i for i in range(10)]
...

Ordinary functions and Lambda Difference of function

  1. There is no name Lambda Function has no name , Ordinary operations have a proper name .

  2. Lambda Function has no return value Use def Keyword to build a common function return value or sequence data type , But in Lambda Function returns a complete procedure . Suppose we want to check whether the number is even or odd , Use lambda The function syntax is similar to the following code snippet .

b = lambda x: "Even" if x%2==0 else "Odd"
b(9)
  1. The function is only on one line Lambda Functions are written and created on only one line , Use indents in the of ordinary functions

  2. Not for code reuse Lambda Functions cannot be used for code reuse , Or you can't import this function in any other file . contrary , Common functions are used for code reuse , Can be used in external files .

Why use Lambda function ?

In general , We don't use Lambda function , Instead, use it with higher-order functions . A higher-order function is a function that requires multiple functions to complete a task , Or when a function returns any other function , You can choose to use Lambda function .

What is a higher-order function ?

Understand higher-order functions through an example . Suppose you have a list of integers , Three outputs must be returned .

  • The sum of all even numbers in a list

  • The sum of all odd numbers in a list

  • The sum of all numbers divisible by three

First, let's assume that ordinary functions are used to deal with this problem . under these circumstances , Three different variables will be declared to store each task , And use a for Loop processing and return the result of three variables . This method can run normally .

Now use Lambda Function to solve this problem , Then you can use three different Lambda Function to check whether a number to be verified is even , Odd number , It can still be divided by three , Then add a number to the result .

def return_sum(func, lst):
result = 0
for i in lst:
#if val satisfies func
if func(i):
result = result + i
return result
lst = [11,14,21,56,78,45,29,28]
x = lambda a: a%2 == 0
y = lambda a: a%2 != 0
z = lambda a: a%3 == 0
print(return_sum(x, lst))
print(return_sum(y, lst))
print(return_sum(z, lst))

Here we create a higher-order function , Among them, the Lambda The function is passed as a part to an ordinary function . In fact, this type of code can be seen everywhere on the Internet . However, many people are using Python This function is ignored when , Or just use it occasionally , But in fact, these functions are really very convenient , It also saves more lines of code . Next, let's look at these higher-order functions .

Python Built in higher order function

Map function

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

Map Function is a function that takes two arguments . The first parameter function Call... With each element in the parameter sequence function function , The second is any iterative sequence data type . Return contain every time function The function returns a new list of values .

map(function, iterable, ...)

Map Function will define some type of operation in the iterator object . Suppose we want to square the elements of the array , That is, the square of each element of an array is mapped to another array that produces the desired result .

arr = [2,4,6,8]
arr = list(map(lambda x: x*x, arr))
print(arr)

We can use... In different ways Map function . Suppose you have a name that contains 、 Dictionary list of address and other details , The goal is to generate a new list of all names .

students = [
{
"name": "John Doe",
"father name": "Robert Doe",
"Address": "123 Hall street"
},
{

"name": "Rahul Garg",
"father name": "Kamal Garg",
"Address": "3-Upper-Street corner"
},
{

"name": "Angela Steven",
"father name": "Jabob steven",
"Address": "Unknown"
}
]
print(list(map(lambda student: student['name'], students)))
>>> ['John Doe', 'Rahul Garg', 'Angela Steven']

The above operations usually occur in scenarios such as fetching data from a database or network .

Filter function

Filter Function filters out data according to given specific conditions . That is, set the filter conditions in the function , Iterative elements , Keep the return value as True The elements of .Map Function operates on each element , and filter The function only outputs elements that meet specific requirements .

Suppose there is a list of fruit names , The task is to output only those names that contain characters “g” The name of .

fruits = ['mango', 'apple', 'orange', 'cherry', 'grapes']
print(list(filter(lambda fruit: 'g' in fruit, fruits)))

filter(function or None, iterable) --> filter object

Returns an iterator , For those functions or terms that are really iteratable . If the function is None, The item returned as true .

Reduce function

This function is special , No Python Built in functions for , Need to pass through from functools import reduce Import .Reduce Returns a single output value from a sequence data structure , It reduces the number of elements by applying a given function .

reduce(function, sequence[, initial]) -> value

A function that will contain two arguments (function) The accumulation is applied to the sequence (sequence) The item , From left to right , So that the sequence reduce To single value .

If there is initial, Put its item before , And as the default value, the sequence is empty .

Suppose you have a list of integers , And find the sum of all elements . And the use of reduce Function instead of using for Loop to deal with this problem .

from functools import reduce
lst = [2,4,6,8,10]
print(reduce(lambda x, y: x+y, lst))
>>> 30

You can also use reduce Function instead of for Loop to find the largest or smallest element from the list .

lst = [2,4,6,8]
# Find the largest element 
print(reduce(lambda x, y: x if x>y else y, lst))
# Find the smallest element 
print(reduce(lambda x, y: x if x<y else y, lst))

Alternative methods for higher-order functions

List derivation

In fact, the list derivation is just a for loop , Used to add each item in the new list , To create a new list from an existing index or a set of elements . Before using map、filter and reduce The completed work can also be completed by list derivation . However , Compared to using Map and filter function , Many people prefer list derivation , Maybe it's because it's easier to use and remember .

Similarly, use list derivation to square each element in the array , The example of fruit can also be solved by list derivation .

arr = [2,4,6,8]
arr = [i**2 for i in arr]
print(arr)
fruit_result = [fruit for fruit in fruits if 'g' in fruit]
print(fruit_result)

Dictionary derivation

Same as list derivation , Use dictionary derivation to create a new dictionary from an existing dictionary . You can also create a dictionary from a list .

Suppose you have a list of integers , Need to create a dictionary , Where the key is each element in the list , The value is the square of each element in the list .

lst = [2,4,6,8]
D1 = {
item:item**2 for item in lst}
print(D1)
>>> {
2: 4, 4: 16, 6: 36, 8: 64}
# Create a dictionary that contains only odd elements 
arr = [1,2,3,4,5,6,7,8]
D2 = {
item: item**2 for item in arr if item %2 != 0}
print(D2)
>>> {
1: 1, 3: 9, 5: 25, 7: 49}

A simple application

How to quickly find the common key of multiple dictionaries

Method 1

dl = [d1, d2, d3] # d1, d2, d3 For the dictionary , The target finds the common key of all dictionaries 
[k for k in dl[0] if all(map(lambda d: k in d, dl[1:]))]
example
dl = [{
1:'life', 2: 'is'},
{
1:'short', 3: 'i'},
{
1: 'use', 4: 'python'}]
[k for k in dl[0] if all(map(lambda d: k in d, dl[1:]))]
# 1
analysis
# List expression traversal dl The key in the first dictionary in 
[k for k in dl[0]]
# [1, 2]
# lambda Anonymous function determines the key in the dictionary , namely k Whether the value is in the rest of the dictionary 
list(map(lambda d: 1 in d, dl[1:]))
# [True, True]
list(map(lambda d: 2 in d, dl[1:]))
#[False, False]
# The list expression condition is the above result ([True, True]) All for True, Then output the corresponding k value 
#1

Method 2

# Using the collection (set) The intersection operation of 
from functools import reduce
# reduce(lambda a, b: a*b, range(1,11)) # 10!
reduce(lambda a, b: a & b, map(dict.keys, dl))

At the end

I have learned Lambda What is a function , as well as Lambda Some ways to use functions . Then we studied together Python Higher order functions in , And how to use... In higher-order functions lambda function .

besides , Also learned the alternative methods of higher-order functions : Perform the previous operation in list derivation and dictionary derivation . Although these methods seem simple , Or you've seen this kind of method before , But you probably don't use them very much . You can try to use them in other more complex functions , To make the code more concise .

Technical communication

At present, a technical exchange group has been opened , Group friends have exceeded 3000 people , The best way to add notes is : source + Interest direction , Easy to find like-minded friends

The way ①、 Send the following picture to wechat , Long press recognition , The background to reply : Add group ;
The way ②、 Add microsignals :dkl88191, remarks : come from CSDN
The way ③、 WeChat search official account :Python Learning and data mining , The background to reply : Add group


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