python中关于内置函数filter的详解

这篇文章主要介绍了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:可迭代对象。

例:

立即学习“Python免费学习笔记(深入)”;

     过滤列表[‘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 nlprint(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') + 1def distinguish(func, array): nl = [] for s in array:  if func(s):   nl.append(s) return nlprint(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 nlprint(distinguish(lambda s: s.rfind('text') + 1, l3))

登录后复制

以上就是python中关于内置函数filter的详解的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2272015.html

(0)
上一篇 2025年2月27日 12:36:39
下一篇 2025年2月27日 12:37:00

AD推荐 黄金广告位招租... 更多推荐

发表回复

登录后才能评论