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

yipeiwu_com5年前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计算玩彩票赢钱概率

使用Python计算玩彩票赢钱概率

工具:Jupyter notebook + Anaconda 游戏规则:时时彩一种玩法是买尾号。2元一个数字,中奖是20元。每个数字出现的概率相等。 目前想到两种买法: 随机购买,...

Django的信号机制详解

Django提供一种信号机制。其实就是观察者模式,又叫发布-订阅(Publish/Subscribe) 。当发生一些动作的时候,发出信号,然后监听了这个信号的函数就会执行。 Django...

python实现获取序列中最小的几个元素

本文实例讲述了python实现获取序列中最小的几个元素。分享给大家供大家参考。 具体方法如下: import heapq import random def issorted(d...

Python实现批量转换文件编码的方法

本文实例讲述了Python实现批量转换文件编码的方法。分享给大家供大家参考。具体如下: 这里将某个目录下的所有文件从一种编码转换为另一种编码,然后保存 import os impor...

Python mutiprocessing多线程池pool操作示例

Python mutiprocessing多线程池pool操作示例

本文实例讲述了Python mutiprocessing多线程池pool操作。分享给大家供大家参考,具体如下: python — mutiprocessing 多线程 pool 脚本代...