py-day4 python filter函数

filter函数:遍历序列中的每个元素,判断每个元素得到布尔值,如果是True则留下

# 例子:条件筛选
name =['m_xiaoli','zhangfei','m_xiaoma','m_wangyun']
ret = []
def test(name):
for i in name:
if not i.startswith("m"):
ret.append(i)
return ret
print(test(name)) ['zhangfei'] def test1(array): # (最好不要用全局变量,自己定义一个变量如左)
for i in array:
if not i.startswith("m"):
ret.append(i)
return ret
print(test1(name))
['zhangfei']
# 在写程序时尽量不要把函数写死,
name =['xiaoli_d','zhangfei','xiaoma_d','m_wangyun']
ret = []
def qu_d(n):            # 定义灵活的函数
return n.endswith('_d')
def qu_m(w):
return w.startswith('m_')
def test(func,array):
for i in array:
if not func(i):
ret.append(i)
return ret
ret = test(qu_d,name) ref = []
def test2(func2,array2):
for p in array2:
if not func2(p):
ref.append(p)
return ref
ref = test2(qu_m,name) print('不是_d结尾的:',ret)
print('不是m_开头的:',ref) 不是_d结尾的: ['zhangfei', 'm_wangyun']
不是m_开头的: ['xiaoli_d', 'zhangfei', 'xiaoma_d']
 #不定义,用lamnda函数也可以
name =['xiaoli_d','zhangfei','xiaoma_d','m_wangyun']
ret = []
def test(func,array):
for i in array:
if not func(i):
ret.append(i)
return ret
ret = test(lambda i:i.endswith('_d'),name)
print('不是_d结尾的:', ret) 不是_d结尾的: ['zhangfei', 'm_wangyun']
# 终极版 filter函数
name =['xiaoli_d','zhangfei','xiaoma_d','m_wangyun']
ret = []
def test(func,array):
for i in array:
if not func(i):
ret.append(i)
return ret
ret = filter(lambda i:not i.endswith('_d'),name)
print('不是_d结尾的:',list(ret)) 不是_d结尾的: ['zhangfei', 'm_wangyun']
上一篇:StringWriter/PrintWriter在Java输出异常信息中的作用


下一篇:filter(函数,可以迭代的对象)