当前位置:   article > 正文

python 之 匿名函数

匿名函数

1. 匿名函数

lambda x , y : x + y
  • 1
'
运行
  • 匿名的目的就是要没有名字,给匿名函数赋给一个名字是没有意义的
  • 匿名函数的参数规则、作用域关系与有名函数是一样的
  • 匿名函数的函数体通常应该是 一个表达式,该表达式必须要有一个返回值
f=lambda x,n:x ** n
print(f(2,3))
  • 1
  • 2
'
运行

2. lambda匿名函数的应用

2.1 max函数

2.1.1 max函数源码

def max(*args, key=None): # known special case of max
    """
    max(iterable, *[, default=obj, key=func]) -> value
    max(arg1, arg2, *args, *[, key=func]) -> value
    
    With a single iterable argument, return its biggest item. The
    default keyword-only argument specifies an object to return if
    the provided iterable is empty.
    With two or more arguments, return the largest argument.
    """
    pass
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
'
运行

2.1.2 max函数使用

# 1.示例,求数组中最大值
max([11, 22, 33, 44, 55])
# 2.求最高薪水
salaries={'egon':3000, 'alex':100000000, 'wupeiqi':10000,  'yuanhao':2000}
# 常规做法
def get_salary(k):
	return salaries[k]
print(max(salaries, key=get_salary)) #'alex'
# 使用lambda表达式
print(max(salaries, key=lambda x:salaries[x]))

# 3.求最高薪水
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']))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
'
运行

2.2 min函数

2.2.1 min函数源码

def min(*args, key=None): # known special case of min
    """
    min(iterable, *[, default=obj, key=func]) -> value
    min(arg1, arg2, *args, *[, key=func]) -> value
    
    With a single iterable argument, return its smallest item. The
    default keyword-only argument specifies an object to return if
    the provided iterable is empty.
    With two or more arguments, return the smallest argument.
    """
    pass
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
'
运行

2.2.2 min函数使用

# 1.示例,求数组中最小值
min([11, 22, 33, 44, 55])
# 2.求最低薪水
salaries={'egon':3000, 'alex':100000000, 'wupeiqi':10000,  'yuanhao':2000}
# 常规做法
def get_salary(k):
	return salaries[k]
print(min(salaries, key=get_salary)) #'alex'
# 使用lambda表达式
print(min(salaries, key=lambda x:salaries[x]))

# 3.求最低薪水
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']))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
'
运行

2.3 sorted函数

2.3.1 sorted函数源码

def sorted(*args, **kwargs): # real signature unknown
    """
    Return a new list containing all items from the iterable in ascending order(升序).
    
    A custom key function can be supplied to customize the sort order, and the
    reverse flag can be set to request the result in descending order.
    """
    pass
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
'
运行

2.3.2 sorted函数使用

# 1.示例,从小到大排序
sorted([11, 22, 99, 44, 55])
# 2.按薪资升序排列
salaries={'egon':3000, 'alex':100000000, 'wupeiqi':10000,  'yuanhao':2000}
# 默认按照字典的键排序
alaries=sorted(salaries)# 使用lambda表达式
# salaries=sorted(salaries,key=lambda x:salaries[x])  #默认是升序排
alaries=sorted(salaries,key=lambda x:salaries[x],reverse=True) #降序

# 3.按薪资升序排列
info = [{'name': 'egon', 'age': '18', 'salary': '3000'}, 
	    {'name': 'wxx', 'age': '28', 'salary': '1000'}, 
	    {'name': 'lxx', 'age': '38', 'salary': '2000'}]
sorted(info, key=lambda dic: int(dic['salary']))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

2.4 map函数

2.4.1 map函数源码

class map(object):
    """
    map(func, *iterables) --> map object
    
    Make an iterator that computes the function using arguments from
    each of the iterables.  Stops when the shortest iterable is exhausted.
    """
    def __getattribute__(self, *args, **kwargs): # real signature unknown
        """ Return getattr(self, name). """
        pass

    def __init__(self, func, *iterables): # real signature unknown; restored from __doc__
        pass

    def __iter__(self, *args, **kwargs): # real signature unknown
        """ Implement iter(self). """
        pass

    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __next__(self, *args, **kwargs): # real signature unknown
        """ Implement next(self). """
        pass

    def __reduce__(self, *args, **kwargs): # real signature unknown
        """ Return state information for pickling. """
        pass
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
'
运行

2.4.2map函数使用

映射, 循环让每个元素执行函数,将每个函数执行的结果保存到新的列表中

# 示例1
v1 = [11,22,33,44]
result = map(lambda x:x+100, v1) # 第一个参数为执行的函数,第二个参数为可迭代元素.
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))
# 示例2
print map(lambda x: x + 1, [y for y in range(10)])

# map(lambda <自变量>:<函数>,<自变量的取值范围>)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

2.5 reduce函数

2.5.1 reduce函数源码

def reduce(function, sequence, initial=None): # real signature unknown; restored from __doc__
    """
    reduce(function, sequence[, initial]) -> value
    
    Apply a function of two arguments cumulatively to the items of a sequence,
    from left to right, so as to reduce the sequence to a single value.
    For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
    ((((1+2)+3)+4)+5).  If initial is present, it is placed before the items
    of the sequence in the calculation, and serves as a default when the
    sequence is empty.
    """
    pass
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
'
运行

2.5.2 reduce函数使用

对参数序列中元素进行累积

from functools import reduce
v1 = ['wo','hao','e']def func(x,y):
    return x+y

print(reduce(func, v1))   # wohaoe
print(lambda x, y: x + y, v1)   # wohaoe
​
ll=['my','name','is','alex','alex','is','sb']
res=reduce(lambda x,y:x+' '+y+' ',ll)
print(res)

# reduce(lambda <自变量>:<函数>,<自变量的取值范围>)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

2.6 filter函数

2.6.1 filter函数源码

class filter(object):
    """
    filter(function or None, iterable) --> filter object
    
    Return an iterator yielding those items of iterable for which function(item)
    is true. If function is None, return the items that are true.
    """
    def __getattribute__(self, *args, **kwargs): # real signature unknown
        """ Return getattr(self, name). """
        pass

    def __init__(self, function_or_None, iterable): # real signature unknown; restored from __doc__
        pass

    def __iter__(self, *args, **kwargs): # real signature unknown
        """ Implement iter(self). """
        pass

    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __next__(self, *args, **kwargs): # real signature unknown
        """ Implement next(self). """
        pass

    def __reduce__(self, *args, **kwargs): # real signature unknown
        """ Return state information for pickling. """
        pass
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
'
运行

2.6.2 filter函数使用

v1 = [11,22,33,'asd',44,'xf']# 一般做法
def func(x):
    if type(x) == int:
        return True
    return False
result = filter(func,v1)
print(list(result))     # [11,22,33,44]# 简化做法
print(list(filter(lambda x: True if type(x) == int else False ,v1)))# 极简做法
print(list(filter(lambda x: type(x) == int ,v1)))

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']

info = [{'name': 'egon', 'age': '18', 'salary': '3000'},
        {'name': 'wxx', 'age': '28', 'salary': '1000'},
        {'name': 'lxx', 'age': '38', 'salary': '2000'}]
oo = filter(lambda x: int(x['salary']) > 1000, info)
print(list(oo))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/小桥流水78/article/detail/958951
推荐阅读
相关标签
  

闽ICP备14008679号