Python数组条件过滤filter函数使用示例,pythonfilter
Python数组条件过滤filter函数使用示例,pythonfilter
使用filter函数,实现一个条件判断函数即可。
比如想过滤掉字符串数组中某个敏感词,示范代码如下:
#filter out some unwanted tags def passed(item): try: return item != "techbrood" #can be more a complicated condition here except ValueError: return False org_words = [["this","is"],["demo","from"],["techbrood"]] words = [filter(passed, item) for item in org_words]
注意Python2.x和Python3.x对于filter/map的处理并不兼容,在Python2.x里面直接返回一个list.
在Python3.x里返回一个iterable对象,比如<filter object at 0x000000000251C978>,后面那串数字是对象引用地址。
可以使用list(words)转换。
map是把函数调用的结果放在列表里面返回,它也可以接受多个 iterable,在第n次调用function时,将使用iterable1[n], iterable2[n], ...作为参数。
filter(function, iterable)
这个函数的功能是过滤出iterable中所有以元素自身作为参数调用function时返回True或bool(返回值)为True的元素并以列表返回.
def f_large_than_5(x):
return x > 5
filter(f_large_than_5, range(10))
>>[6,7,8,9]
3.x 返回的是一个iter obj,如果想返还【】,要加上list()
>>> list(filter(bigger_than_five,[1,10]))
[6, 7, 8, 9, 10]
其实3.x里面,达到你的这个目的的最简单的方法就直接:
>>> [x for x in range(11) if x > 5]
[6, 7, 8, 9, 10]
相关内容
- 使用python编写android截屏脚本双击运行即可,pythonandro
- python中的内置函数getattr()介绍及示例,pythongetattr
- 用python代码做configure文件,
- python中from module import * 的一个坑,pythonmodule
- python 示例分享---逻辑推理编程解决八皇后,python逻辑推
- python实现多线程采集的2个代码例子,python多线程
- python中使用urllib2伪造HTTP报头的2个方法,pythonurllib2
- Python中使用urllib2防止302跳转的代码例子,pythonurllib2
- python中使用urllib2获取http请求状态码的代码例子,pyth
- python基于mysql实现的简单队列以及跨进程锁实例详解,
评论关闭