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