Python: Anonymous Function

Source: Internet
Author: User
Keywords python anonymous function python anonymous function

When we pass in a function, sometimes it is not necessary to define the function explicitly, and it is more convenient to pass in the anonymous function directly. In Python, there is limited support for anonymous functions


lambda x, y: x+y
1 The purpose of anonymity is to have no name, it is meaningless to assign a name to an anonymous function

2 The parameter rules and scope relationships of anonymous functions are the same as those of famous functions

3 The function body of an anonymous function should usually be an expression, which must have a return value

f=lambda x,n:x ** n
print(f(2,3))
Application of lambda anonymous functions: **max, min, sorted, map, reduce, filter**

The person with the highest salary: max


salaries={
    'egon':3000,
    'alex':100000000,
    'wupeiqi':10000,
    'yuanhao':2000
}
def get(k):
    return salaries[k]
print(max(salaries,key=get)) #'alex'
print(max(salaries,key=lambda x:salaries[x]))
info = [
    {'name':'egon','age': '18','salary': '3000'},
    {'name':'wxx','age': '28','salary': '1000'},
    {'name':'lxx','age': '38','salary': '2000'}
]
max(info, key=lambda dic: int(dic['salary']))
max([11, 22, 33, 44, 55])

The person with the lowest wage: min

salaries={
    'egon':3000,
    'alex':100000000,
    'wupeiqi':10000,
    'yuanhao':2000
}
print(min(salaries,key=lambda x:salaries[x])) #'yuanhao'
 info=[
            {'name':'egon','age':'18','salary':'3000'},
            {'name':'wxx','age':'28','salary':'1000'},
            {'name':'lxx','age':'38','salary':'2000'}
        ]
min(info,key=lambda dic:int(dic['salary']))

Sort the salary dictionary, sort by salary level


salaries={
    'egon':3000,
    'alex':100000000,
    'wupeiqi':10000,
    'yuanhao':2000
}
alaries=sorted(salaries) # sort by dictionary keys by default
print(salaries)

# salaries=sorted(salaries,key=lambda x:salaries[x]) #default is ascending sort
alaries=sorted(salaries,key=lambda x:salaries[x],reverse=True) #descending order
print(salaries)
info=[
            {'name':'egon','age':'18','salary':'3000'},
            {'name':'wxx','age':'28','salary':'1000'},
            {'name':'lxx','age':'38','salary':'2000'}
        ]
l=sorted(info,key=lambda dic:int(dic['salary']))

map mapping, loop to let each element execute the function, save the results of each function execution to a new list

v1 = [11,22,33,44]
result = map(lambda x:x+100,v1) # The first parameter is the executed function, and the second parameter is the iterable element.
print(list(result)) # [111,122,133,144]
names=['alex','wupeiqi','yuanhao','egon']
res=map(lambda x:x+'_NB' if x =='egon' else x +'_SB',names)
print(list(res))
reduce, accumulate the elements in the parameter sequence.


import functools
v1 = ['wo','hao','e']

def func(x,y):
    return x+y
result = functools.reduce(func,v1)
print(result) # wohaoe

result = functools.reduce(lambda x,y:x+y,v1)
print(result) # wohaoe

from functools import reduce
l=['my','name','is','alex','alex','is','sb']
res=reduce(lambda x,y:x+''+y+'',l)
print(res)
#my name is alex alex is sb

filter, filter by conditions.


result=filter(lambda x:x> 2,[1,2,3,4])
print(list(result))
v1 = [11,22,33,'asd',44,'xf']

# General practice
def func(x):
    if type(x) == int:
        return True
    return False
result = filter(func,v1)
print(list(result)) # [11,22,33,44]

# Simplified approach
result = filter(lambda x: True if type(x) == int else False, v1)
print(list(result))

# Minimalist approach
result = filter(lambda x: type(x) == int, v1)
print(list(result))
names=['alex_sb','wxx_sb','yxx_sb','egon']
res=filter(lambda x:True if x.endswith('sb') else False,names)
res=filter(lambda x:x.endswith('sb'),names)
print(list(res)) #['alex_sb','wxx_sb','yxx_sb']
ages=[18,19,10,23,99,30]
res=filter(lambda n:n >= 30,ages)
print(list(res)) #[99, 30]
salaries={
    'egon':3000,
    'alex':100000000,
    'wupeiqi':10000,
    'yuanhao':2000
}
res=filter(lambda k:salaries[k] >= 10000,salaries)
print(list(res)) #['alex','wupeiqi']
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.