python中匿名函数的用法_python 匿名函数用法及应用

map function

It applies the function to each element in list or set.

>>> def f(x):

... return x * x

>>> example = [1, 2, 3, 4, 5]

>>> map(f, example)

[1, 4, 9, 16, 25]

reduce function

It is used for continuously operation of a sequences.

>>> from functools import reduce

>>> def add(x, y):

... return x + y

>>> reduce(add, [1, 2, 3])

6 (1 + 2 + 3)

lambda function

3.1 lambda parameter : operation

def f(x):

return x * x

equals to

lambda x : x * x

3.2 lambda function as the return value

def add(string, i):

return lambda: int(string) + I

3.3 lambda nesting

>>> action = (lambda x : (lambda y : x + y))

>>> a = action(10)

>>> a(5)

15

Here are many applications of map and reduce

4.1 str2int

from functools import reduce

DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}

def str2int(s):

def func(x, y):

return x + 10*y

def char2num(c):

return DIGITS[c]

return reduce(func, map(char2num, s))

4.2 normalize the English name ex. [Lisa, BarrY, TOM] -> [Lisa, Barry, Tom]

def normalize(name):

sub_name = name[1:].lower()

first = name[0].upper()

return str(first) + str(sub_name)

>>> L1 = ['adam', 'LISA', 'barT']

>>> L2 = list(map(normalize, L1))

[Adam, Lisa, Bart]

4.3 str2float

CHAR_TO_FLOAT = { '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5,

'6': 6, '7': 7, '8': 8, '9': 9, '.': -1}

def str2float(s):

point = 0

def to_float(x, y):

nonlocal point # use the variable from outer function

if y = -1: # meet the point

point = 1

return x

if point = 0: # the integer part

return x*10 + y

elif point = 1: # the decimal part

point = point * 10

return x + y / point

return reduce(to_float, map(lambda ch : CHAR_TO_FLOAT[ch], s))

4.4 Find the person with highest salary.

salaries={

'egon':3000,

'alex':100000000,

'wupeiqi':10000,

'yuanhao':2000

}

max_salary = max(salaries, key = lambda x : salaries[x])

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值