目录
- filter
- map
- reduce
filter功能
- 对循环根据过滤条件进行过滤并生成迭代器
filter用法
-
用法:
filter(func, list)
-
参数介绍:
-
func
: 对list每个item进行条件过滤的定义 -
list
:需要过滤的列表
-
filter举例:
res = tilter(lambda x:x >1,[0,1,2])
返回值:
<filter at Ox4f3af70>->[1,2]
map
对列表中的每个成员是否满足条件返回对应的True与False
-
用法:
map(func, list)
-
参数介绍:
-
func
:对 list每个item进行条件满足的判断 -
list
:需要过滤的列表
-
举例:
res = map(lambda x:x > 1,[0,1,2])
返回值:
<map at 0x4f3af70>->[False, False,True]
reduce
- 对循环前后两个数据进行累加
- 用法∶
reduce(func, list)
- 参数介绍:
func
:对数据累加的函数
list
:需要处理的列表 - 举例:
res =reduce(lambda x,y:x +y,[0,1,2])
- 返回值:
数字->3
reduce的导入
from functools import reduce
实战
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2021/8/27 21:15
# @Author : InsaneLoafer
# @File : package_filter.py
from functools import reduce
fruits = ['apple', 'banana', 'orange']
result = filter(lambda x:'e' in x, fruits)
print(list(result))
def filter_func(item):
if 'e' in item:
return True
print('--------')
filter_result = filter(filter_func, fruits)
print(list(filter_result))
map_result = map(filter_func, fruits)
print(list(map_result))
reduce_result = reduce(lambda x,y:x+y, [0,1,2,4])
print(reduce_result)
reduce_result_str = reduce(lambda x,y:x+y, fruits)
print(reduce_result_str)
['apple', 'orange']
--------
['apple', 'orange']
[True, None, True]
7
applebananaorange
Process finished with exit code 0