Python高阶函数与lambda表达式

It is okay to fail, as long as you keep trying! ——《科学怪狗》

只要你坚持尝试,失败也没有关系!

lambda表达式

  为了避免创建一次性的辅助性函数

语法

1
lambda <argument>, <expression>

map()

  根据提供的函数对指定序列做映射。返回包含每次函数返回值的新列表。

语法

1
map(function, iterable, ...)

将一个包含整数的列表转换为这些整数字符串的另一个列表

1
2
3
4
5
6
7
8
# for循环实现
oldList = list(range(1, 5))
newList = []
for num in oldList:
newList.append(str(num))
print(newList)

>>>['1', '2', '3', '4']
1
2
3
4
5
6
# map实现
oldList = list(range(1, 5))
newList = list(map(str, oldList))
print(newList)

>>>['1', '2', '3', '4']

计算平方和

1
2
3
4
5
6
7
# map + 函数实现
def square(x):
return x ** 2
res = list(map(square, list(range(1, 5))))
print(res)

>>>[1, 4, 9, 16]
1
2
3
4
5
# map + lambda实现
res = list(map(lambda x: x**2, list(range(1, 5))))
print(res)

>>>[1, 4, 9, 16]

filter()

  过滤掉序列中不符合条件的元素,返回由符合条件元素组成的新列表。返回一个迭代器对象,如果要转换为列表,可以使用 list() 来转换。

语法

1
filter(function, iterable)

过滤出列表中的所有奇数

1
2
3
4
5
6
7
8
# filter + 函数实现
def is_odd(n):
return n % 2 == 1
tmplist = filter(is_odd, list(range(1, 11)))
newlist = list(tmplist)
print(newlist)

>>>[1, 3, 5, 7, 9]
1
2
3
4
5
6
# filter + lambda实现
tmplist = filter(lambda x: x % 2 == 1, list(range(1, 11)))
newlist = list(tmplist)
print(newlist)

>>>[1, 3, 5, 7, 9]

reduce()

  对参数序列中元素进行累积。函数将一个数据集合(列表,元组等)中的所有数据进行下列操作:用传给 reduce 中的函数 function(有两个参数)先对集合中的第 1、2 个元素进行操作,得到的结果再与第三个数据用 function 函数运算,最后得到一个结果。

语法

1
reduce(function, iterable[, initializer])

计算一个整数列表的和

1
2
3
4
5
6
7
8
9
# reduce + 函数实现
from functools import reduce

def add(x, y):
return x + y
res = reduce(add, list(range(1, 5)))
print(res)

>>>10
1
2
3
4
5
6
7
# reduce + lambda实现
from functools import reduce

res = reduce(lambda x, y: x+y, list(range(1, 5)))
print(res)

>>>10

参考文章:
Python map() 函数 | 菜鸟教程
Python filter() 函数 | 菜鸟教程
Python reduce() 函数 | 菜鸟教程