Python commonly used functions map, fiftyer, reduce

Python commonly used functions map, fiftyer, reduce

map mapping function

"""
循环遍历li列表内容,然后将每个元素*2,再存到匿名函数x中
"""
li = [1, 2, 3, 4, 5, 6]
res = map(lambda x: x*2, li)
print(list(res))
# 输出结果
[2, 4, 6, 8, 10, 12]

filter filter function

"""
循环遍历li列表内容,将大于的元素放置匿名函数中
"""
li = [1, 2, 3, 4, 5, 6]
res = filter(lambda x: x > 3, li)
print(list(res))
# 输出结果
[4, 5, 6]

reduce function

from functools import reduce


"""
在100的基础上加列表中的元素
100 + 1 + 2   103
103 + 3       106
106 + 4       110
...
115 + 6       121
"""
# 使用方法1,通过匿名函数lambds
li = [1, 2, 3, 4, 5, 6]
# 最后一个参数100非必填
res = reduce(lambda x, y: x+y, li, 100)
print(res)
# 输出结果
121

# 使用方法2,通过自定义函数
# 原理与方法1类似,主要区别函数对象不一致
def add(a, b):
	return a + b

res = reduce(add, li, 100)
# 输出结果
121

Guess you like

Origin blog.csdn.net/weixin_44102466/article/details/112800394