Python 函数之lambda、map、filter和reduce

 1、lambda函数

lambda()是Python里的匿名函数,其语法如下:

lambda [arg1[, arg2, ... argN]]: expression


学习条件运算时,对于简单的 if else 语句,可以使用三元运算来表示,即:

# 普通条件语句
if 1 == 1:
    name = 'evescn'
else:
    name = 'gm'
  
# 三元运算
name = 'evescn' if 1 == 1 else 'gm'

对于简单的函数,也存在一种简便的表示方式,即:lambda表达式

# ###################### 普通函数 ######################
# 定义函数(普通方式)
def func(arg):
    return arg + 1
  
# 执行函数
result = func(123)
  
# ###################### lambda ######################
  
# 定义函数(lambda表达式)
my_lambda = lambda arg : arg + 1
  
# 执行函数
result = my_lambda(123)

lambda存在意义就是对简单函数的简洁表示,下面在举一个列表的例子

l = [11, 22, 33, 44]

new_l = map(lambda x: x + 10, l)

a = list(new_l)
print(a)

# 输出结果
[21, 32, 43, 54]

 2、map函数

map函数会根据提供的函数对指定序列做映射。
map函数的定义:
map(function, sequence[, sequence, ...]) 

map 函数会对序列参数 sequence 中的每个元素调用 function 函数,返回的结果为每一个元素调用function函数的返回值

 

l = [11, 22, 33, 44]

def myadd(x):
    return x + 10

new_n = map(myadd, l)

b = list(new_n)
print(b)

# 输出结果
[21, 32, 43, 54]

利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。输入:['adam', 'LISA', 'barT'],输出:['Adam', 'Lisa', 'Bart'] 

# -*- coding: utf-8 -*-

def normalize(str):
    return str.capitalize()

# 测试:
L1 = ['adam', 'LISA', 'barT', 'ROOT']
L2 = list(map(normalize, L1))
print(L2)

# 输出结果
['Adam', 'Lisa', 'Bart', 'Root'

 3、filter 函数

对于序列中的元素进行筛选,最终获取符合条件的序列

 

  

def myfunc(x):
    if x > 30:
        return True
    else:
        return False

a = [11, 22, 33]

new_a = filter(myfunc,a)

b = list(new_a)
print(b)

# 输出结果
[33]

 4、reduce函数

对于序列内所有元素进行累计操作

 reduce把一个函数作用在一个序列[x1, x2, x3, ...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算,其效果就是:
reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)

 

 

比方说对一个序列求和,就可以用reduce实现:

>>> from functools import reduce
>>> def add(x, y):
...     return x + y
...
>>> reduce(add, [1, 3, 5, 7, 9])
25

当然求和运算可以直接用Python内建函数sum(),没必要动用reduce

但是如果要把序列[1, 3, 5, 7, 9]变换成整数13579reduce就可以派上用场:

>>> from functools import reduce
>>> def fn(x, y):
...     return x * 10 + y
...
>>> reduce(fn, [1, 3, 5, 7, 9])
13579

这个例子本身没多大用处,但是,如果考虑到字符串str也是一个序列,对上面的例子稍加改动,配合map(),我们就可以写出把str转换为int的函数:

>>> from functools import reduce
>>> def fn(x, y):
...     return x * 10 + y
...
>>> def char2num(s):
...     return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
...
>>> reduce(fn, map(char2num, '13579'))
13579

整理成一个str2int的函数就是:

from functools import reduce

def str2int(s):
    def fn(x, y):
        return x * 10 + y
    def char2num(s):
        return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
    return reduce(fn, map(char2num, s))

还可以用lambda函数进一步简化成:  

from functools import reduce

def char2num(s):
    return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]

def str2int(s):
    return reduce(lambda x, y: x * 10 + y, map(char2num, s))

也就是说,假设Python没有提供int()函数,你完全可以自己写一个把字符串转化为整数的函数,而且只需要几行代码!

转载自:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014317852443934a86aa5bb5ea47fbbd5f35282b331335000

http://www.cnblogs.com/wupeiqi/articles/4943406.html

原文地址:https://www.cnblogs.com/evescn/p/7554478.html