python 内置函数filter

yipeiwu_com5年前Python基础

python 内置函数filter

class filter(object):
 """
 filter(function or None, iterable) --> filter object
 
 Return an iterator yielding those items of iterable for which function(item)
 is true. If function is None, return the items that are true.
 """

filter(func,iterator)

    func:自定义或匿名函数中所得值是布尔值,true将保留函数所取到的值,false则取反。
    iterator:可迭代对象。

例:

     过滤列表['text_test_text', 'test_text_1', 'text_test_2', '3_test_text', 'test_test']
     只要含有text字符串及将其取出 or 取反。

s.rfind'text'+1

     Python3中 rfind() 返回字符串最后一次出现的位置,如果没有匹配项则返回-1。
     数字中0是false,0以上的整数都是true,所以s.rfind'text'后会有+1,没找到字符及-1+1=0.

# Filter

li = ['text_test_text', 'test_text_1', 'text_test_2', '3_test_text', 'test_test']

# 默认保留函数所取到的值
print(list(filter(lambda s: s.rfind('text') + 1, li)))
# 取反,下三个例子是一样的
print(list(filter(lambda s: not s.rfind('text') + 1, li)))

# Noe 自定义函数

l1 = ['text_test_text', 'test_text_1', 'text_test_2', '3_test_text', 'test_test']


def distinguish(l):
 nl = []
 for s in l:
  if s.rfind("text") + 1:
   nl.append(s)
 return nl


print(distinguish(l1))

# Two 自定义高阶函数

l2 = ['text_test_text', 'test_text_1', 'text_test_2', '3_test_text', 'test_test']


def f(s):
 return s.rfind('text') + 1


def distinguish(func, array):
 nl = []
 for s in array:
  if func(s):
   nl.append(s)
 return nl


print(distinguish(f, l2))

# Three 匿名函数

l3 = ['text_test_text', 'test_text_1', 'text_test_2', '3_test_text', 'test_test']


def distinguish(func, array):
 nl = []
 for s in array:
  if func(s):
   nl.append(s)
 return nl

print(distinguish(lambda s: s.rfind('text') + 1, l3))

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

相关文章

python 发送json数据操作实例分析

python 发送json数据操作实例分析

本文实例讲述了python 发送json数据操作。分享给大家供大家参考,具体如下: # !/usr/bin/env python # -*- coding: utf-8 -*-...

Python中random模块用法实例分析

本文实例讲述了Python中random模块用法。分享给大家供大家参考。具体如下: import random x = random.randint(1,4); y = random...

详解安装mitmproxy以及遇到的坑和简单用法

详解安装mitmproxy以及遇到的坑和简单用法

mitmproxy 是一款工具,也可以说是 python 的一个包,在命令行操作的工具。 MITM 即中间人攻击(Man-in-the-middle attack) 使用这个工具可以在...

Python编写一个验证码图片数据标注GUI程序附源码

Python编写一个验证码图片数据标注GUI程序附源码

做验证码图片的识别,不论是使用传统的ORC技术,还是使用统计机器学习或者是使用深度学习神经网络,都少不了从网络上采集大量相关的验证码图片做数据集样本来进行训练。 采集验证码图片,可以直接...

Python操作csv文件实例详解

Python操作csv文件实例详解

一、Python读取csv文件 说明:以Python3.x为例 #读取csv文件方法1 import csv csvfile = open('csvWrite.csv',newl...