python中filter函数
Python 函数 filter
2023-09-11 14:21:07 时间
python中filter()函数
filter()函数是 Python 内置的另一个有用的高阶函数,filter()函数接收一个函数 f 和一个list,这个函数 f 的作用是对每个元素进行判断,返回 True或 False,filter()根据判断结果自动过滤掉不符合条件的元素,返回由符合条件元素组成的新list。
例如,要从一个list [1, 4, 6, 7, 9, 12, 17]中删除偶数,保留奇数,首先,要编写一个判断奇数的函数:
def is_odd(x): return x % 2 == 1
然后,利用filter()过滤掉偶数:
>>>filter(is_odd, [1, 4, 6, 7, 9, 12, 17])
结果:
[1, 7, 9, 17]
利用filter(),可以完成很多有用的功能,例如,删除 None 或者空字符串:
def is_not_empty(s): return s and len(s.strip()) > 0 >>>filter(is_not_empty, ['test', None, '', 'str', ' ', 'END'])
结果:
['test', 'str', 'END']
注意: s.strip(rm) 删除 s 字符串中开头、结尾处的 rm 序列的字符。
当rm为空时,默认删除空白符(包括'\n', '\r', '\t', ' '),如下:
>>> a = ' 123'
>>> a.strip()
'123'
>>> a = '\t\t123\r\n'
>>> a.strip()
'123'
练习:
请利用filter()过滤出1~100中平方根是整数的数,即结果应该是:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
方法:
import math def is_sqr(x): return math.sqrt(x) % 1 == 0 print filter(is_sqr, range(1, 101))
结果:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
相关文章
- Python学习--05函数
- Python学习笔记之常用函数及说明
- Python之 sklearn:sklearn.preprocessing中的StandardScaler函数的简介及使用方法之详细攻略
- Python之多线程:python多线程设计之同时执行多个函数命令详细攻略
- Python之pandas:pandas的get_dummies函数简介(one-hot编码/将字符串似的分类变量转为哑变量/虚拟/伪/指示符变量)及其使用方法之详细攻略
- Python编程语言学习:python中与数字相关的函数(取整等)、案例应用之详细攻略
- Python之多线程:python多线程设计之同时执行多个函数命令详细攻略
- 〖Python WEB 自动化测试实战篇③〗- python-selenium环境配置搭建
- 微信朋友圈自动点赞(Python代码实现)
- 从零开始学python | 使用Python映射,过滤和缩减函数:所有您需要知道的
- 在Python 中如何将类对象序列化为JSON?
- 【LeetCode Python实现】93. 复原IP地址(中等)
- Python学习之四【变量】
- Python标准库:内置函数slice(stop) slice(start, stop[, step])
- python web py入门(39)- javascript的while循环语句
- Python-Django使用MemcachedCache缓存
- 机器学习用什么语言?Python可以学机器学习吗?
- Python中的map、zip、filter、reduce函数使用