Python数组条件过滤filter函数使用示例

yipeiwu_com6年前Python基础

使用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)转换。

相关文章

python: line=f.readlines()消除line中\n的方法

python: line=f.readlines()消除line中\n的方法

测试代码 #!/ust/bin/env python3 f = open("name.txt") date = f.readlines() print(date) f.close(...

Python字典遍历操作实例小结

本文实例讲述了Python字典遍历操作。分享给大家供大家参考,具体如下: 1 遍历键值对 可以使用一个 for 循环以及方法 items() 来遍历这个字典的键值对。 dict =...

python里将list中元素依次向前移动一位

问题 定义一个int型的一维数组,包含10个元素,分别赋值为1~10, 然后将数组中的元素都向前移一个位置, 即,a[0]=a[1],a[1]=a[2],…最后一个元素的值是原来第一个元...

详解django中使用定时任务的方法

今天介绍在django中使用定时任务的两种方式。 方式一: APScheduler 1)安装: pip install apscheduler 2)使用: from apsc...

django 实现将本地图片存入数据库,并能显示在web上的示例

django 实现将本地图片存入数据库,并能显示在web上的示例

1. 将图片存入数据库 关于数据库基本操作的学习,请参见这一篇文章:/post/167141.htm 这里我默认,您已经会了基本操作,能在数据库中存图片了,然后,也会用图形界面操作数据库...