day11 filter函数

场景模拟:我想判断某个列表里面的某个元素怎么怎么样
基础方法,如果需要判断多次则重复代码
 ret = []
move_peole = ["alex","sb_wupeiqi","yangtuo","sb_yuanhao"]
for p in move_peole:
if not p.startswith("sb"):
ret.append(p) print(ret)
函数方法
利用参数更换来多次代入执行,判断方式单一
 move_peole = ["alex","sb_wupeiqi","yangtuo","sb_yuanhao"]
move_peole1 = ["alex","wupeiqi_sb","yangtuo","yuanhao_sb"]
def filter_test(array):
ret = []
for p in array:
if not p.startswith("sb"):
ret.append(p)
return ret print(filter_test(move_peole))
双函数参数调用
解决了方法限定的问题但是代码复杂,代码量大
 move_peole1 = ["alex","wupeiqi_sb","yangtuo","yuanhao_sb"]
def sb_show(n):
return n.endswith("sb")
def filter_test(funk,array):
ret = []
for p in array:
if not funk(p):
ret.append(p)
return ret print(filter_test(sb_show,move_peole1))
终极版本目前可以做到的最好的版本
 def sb_show(n):
return n.endswith("sb")
move_peole1 = ["alex","wupeiqi_sb","yangtuo","yuanhao_sb"]
lambda x:x.endswith("sb")
def filter_test(funk,array):
ret = []
for p in array:
if not funk(p):
ret.append(p)
return ret
print(filter_test(lambda x:x.endswith("sb"),move_peole1))
filter 函数,计算布尔值,得出为true则保留
利用filter可以实现的效果
格式:filter(方法,参数)
 move_peole1 = ["alex","wupeiqi_sb","yangtuo","yuanhao_sb"]
print(filter (lambda x:not x.endswith("sb"),move_peole1))
print(list(filter (lambda x:not x.endswith("sb"),move_peole1)))

上一篇:Helm简介及安装


下一篇:UVA 11000- Bee 递推