Python之filter函数使用示例
程序员文章站
2022-10-29 14:37:11
filter遍历序列中的每一个元素,判断每个元素得到的布尔值,如果是True则留下来 ==> [{'name': 'abc', 'num': 1}, {'name': 'def', 'num': 2}] ......
#!/usr/bin/env python # -*- coding:utf8 -*- ###########
#找出开头(或结尾)不含有ab的字符串并将其提取出来
##########
s = ['ab_iua','sh_ab','a_bak'] print() def filter_start(array): ret = [] for i in array: if not i.startswith('ab'): ret.append(i) return ret print(s) tmp = filter_start(s) print(tmp) ########### print() def filter_test(f,array): tmp = [] for i in array: if not f(i): ###*******### tmp.append(i) return tmp def sb_show(n): return n.endswith('ab') print(s) res = filter_test(sb_show,s) print(res) tmp = filter_test(lambda n:n.endswith("ab"),s) print(tmp) ############## print() ###filter函数 s = ['ab_iua','sh_ab','a_bak'] print(s) print(filter_test(lambda n:n.endswith("ab"),s)) print(list(filter_test(lambda n:n.endswith("ab"),s)))
filter遍历序列中的每一个元素,判断每个元素得到的布尔值,如果是true则留下来
student = [ {'name':'abc','num':1}, {'name':'def','num':2}, {'name':'ljk','num':3}, ] print(list(filter(lambda s:s['num']<=2,student)))
==> [{'name': 'abc', 'num': 1}, {'name': 'def', 'num': 2}]