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

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

以上就是python 内置函数filter。懂得应该怎样生活的人是高尚的,对此浑浑噩噩生活的人则完全可以说是不如奴隶的。省察自己的生活,保护好自己的心灵,去除造成生命痛苦的恶习、恶因,才会让自己成为如意生活的主人,才能摆脱奴隶一般被动受苦的人生。只有在省察中为自己而活,并找到合于真相、真理的良好意义,生活才会变得良好而清醒。更多关于python 内置函数filter请关注haodaima.com其它相关文章!

您可能有感兴趣的文章
Python自动化运维-使用Python脚本监控华为AR路由器关键路由变化

Python自动化运维-netmiko模块设备自动发现

Python自动化运维—netmiko模块连接并配置华为交换机

Python自动化运维-利用Python-netmiko模块备份设备配置

Python自动化运维-Paramiko模块和堡垒机实战