python 内置函数filter
作者:lqh 发布时间:2023-01-07 21:53:37
标签:python,内置函数,filter
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))
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
0
投稿
猜你喜欢
- 目的:在numpy数组中知道指定元素的索引函数: np.argwhere>>>x>>>array([[0
- 对于np.argmax()让我迷惑了很久,尤其是其中的axis=1的比较结果。一、np.argmax()的理解1、最简单的例子假定现在有一个
- 如下所示:<code class="language-python">import numpy as np
- 问题给出一段话,由短句组成,短句之间可能被任意标点符号隔开。想要提取所有的短句。解决使用 re.split 函数,用正则式匹配的方法,一次性
- 如下所示:# coding=utf-8import pandas as pd# 读取csv文件 3列取名为 name,sex,births,
- 1.颜色空间转换使用cv2.cvtColor(input_image ,flag),flag为转换类型常用的转换类型有:BGR和灰度图的转换
- 1. 在 Python 中 XML 文件的编码问题1.Python 使用的xml.etree.ElementTree库只支持解析和生成标准的
- 本文实例讲述了GO语言获取系统环境变量的方法。分享给大家供大家参考。具体实现方法如下:package mainimport ( &
- 一、Pandoc转换1.1 问题由于我们markdown编辑器比较特殊,一般情况下,我们不太好看,如果转换成pdf的话,我们就不需要可以的去
- //我修改之,能正常运行,测试环境为mysql5.0,xp //关键是设置对字符集,设置gbk,gb2312测试通过,utf8测试未通过 /
- 操作数据库时候难免会因为“大意”而误操作,需要快速恢复的话通过备份来恢复是不太可能的,因为需要还原和binlog差来恢复,等不了,很费时。这
- 引言写这个小爬虫主要是为了爬校园论坛上的实习信息,主要采用了Requests库源码URLs.py主要功能是根据一个初始url(包含page页
- 什么是 Goroutinegoroutine 是 Go 并行设计的核心。goroutine 说到底其实就是协程,它比线程更小,十几个 gor
- Yii2 框架 之所以称之为高效快速开发的一款框架,是因为有一个神奇的工具Gii用过Yii1框架的Coder都知道,Gii可以为你快速生成代
- 一、MySQL 逻辑架构概览MySQL 最重要、最与众不同的特性就是它的可插拔存储引擎架构(pluggable storage engine
- 元组的特点:是一种不可变序列,一旦创建就不能修改1、拆包将元组的元素取出赋值给不同变量>>> a = ('hell
- 主要来介绍下Inner Join , Full Out Join , Cross Join , Left Join , Right Join
- 详解Python list 与 NumPy.ndarry 切片之间的区别实例代码:# list 切片返回的是不原数据,对新数据的修改不会影响
- 引言我们经常听到"因为GIL的存在,python的多线程不能利用多核CPU",现在我们暂且不提GIL,python能不能
- 一定要注重代码规范,按照平时的代码管理,可以将Python代码规范检测分为两种:静态本地检测:可以借助静态检查工具,比如:Flake8,Py