源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

python 内置函数filter

  • 时间:2021-08-20 01:33 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要: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.
 """

[b]filter(func,iterator)[/b]     func:自定义或匿名函数中所得值是布尔值,true将保留函数所取到的值,false则取反。     iterator:可迭代对象。 [b]例:[/b]      过滤列表['text_test_text', 'test_text_1', 'text_test_2', '3_test_text', 'test_test']      只要含有text字符串及将其取出 or 取反。 [b]s.rfind'text'+1[/b]      Python3中 rfind() 返回字符串最后一次出现的位置,如果没有匹配项则返回-1。      数字中0是false,0以上的整数都是true,所以s.rfind'text'后会有+1,没找到字符及-1+1=0. [b]# Filter[/b]
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)))

[b]# Noe 自定义函数[/b]
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))

[b]# Two 自定义高阶函数[/b]
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))

[b]# Three 匿名函数[/b]
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)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部