filterobjectReturnaniteratoryieldingthoseitemsofiterableforwhichfunction(item)istrue.IffunctionisNone,returntheitemsthataretrue."""filter(func,iterator)func:" />

python 内置函数filter

系统 1443 0

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))


          

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


更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。

【本文对您有帮助就好】

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描上面二维码支持博主2元、5元、10元、自定义金额等您想捐的金额吧,站长会非常 感谢您的哦!!!

发表我的评论
最新评论 总共0条评论