filter()-过滤序列
- 参数:函数
- 序列
filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。
取奇数序列
示例
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Python filter 用法
# 是否为奇数
def isOdd(x):
return (x % 2) != 0
def filterTest():
# 函数,序列
result = filter(isOdd, [1, 2, 3,4,5])
print(result)
filterTest()
运行结果
D:\PythonProject>python run.py
[1, 3, 5]
删除空字符串
示例代码
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Python filter 用法
# 删除空字符串
def whithoutEmptyString(s):
return s and s.strip()
def filterTest():
# 函数,序列
result = filter(whithoutEmptyString, ["A", "", "B"])
print(result)
filterTest()
运行结果
D:\PythonProject>python run.py
['A', 'B']