filter函数


filter函数
#filter遍历序列中的每个元素,判断每个元素得到布尔值,如果是True则留下来
people=[
{'name':'alex','age':1000},
{'name':'wupei','age':10000},
{'name':'yuanhao','age':9000},
{'name':'linhaifeng','age':18},
]
print(list(filter(lambda p:p['age']<=18,people)))
"D:\pycharm new project\venv\Scripts\python.exe" "D:/pycharm new project/01"
[{'name': 'linhaifeng', 'age': 18}]

 

 


movie_people=['sb_alex','sb_wupeiqi','linhaifeng','sb_yuanhao']

def filter_test(array):
ret=[]
for p in array:
if not p.startswith('sb'): 只要不是sb开头的,就怎么样
ret.append(p)
return ret

res=filter_test(movie_people)
print(res)
"D:\pycharm new project\venv\Scripts\python.exe" "D:/pycharm new project/01"
['linhaifeng']


movie_people=['alex_sb','wupeiqi_sb','linhaifeng','yuanhao_sb']
def sb_show(n):
return n.endswith('sb')

def filter_test(func,array):
ret=[]
for p in array:
if not func(p):
ret.append(p)
return ret

res=filter_test(sb_show,movie_people)
print(res)
"D:\pycharm new project\venv\Scripts\python.exe" "D:/pycharm new project/01"
['linhaifeng']


#终极版本
movie_people=['alex_sb','wupeiqi_sb','linhaifeng','yuanhao_sb']
# def sb_show(n):
# return n.endswith('sb')
#--->lambda n:n.endswith('sb')

def filter_test(func,array):
ret=[]
for p in array:
if not func(p):
ret.append(p)
return ret

res=filter_test(lambda n:n.endswith('sb'),movie_people)
print(res)
"D:\pycharm new project\venv\Scripts\python.exe" "D:/pycharm new project/01"
['linhaifeng']

#filter函数用法
filter(函数逻辑,可迭代对象)
movie_people=['alex_sb','wupeiqi_sb','linhaifeng','yuanhao_sb']
print(filter(lambda n:not n.endswith('sb'),movie_people))
"D:\pycharm new project\venv\Scripts\python.exe" "D:/pycharm new project/01"
<filter object at 0x0000018738C1EB00

res=filter(lambda n:not n.endswith('sb'),movie_people)
print(list(res))
"D:\pycharm new project\venv\Scripts\python.exe" "D:/pycharm new project/01"
['linhaifeng']

print(list(filter(lambda n:not n.endswith('sb'),movie_people)))
"D:\pycharm new project\venv\Scripts\python.exe" "D:/pycharm new project/01"
['linhaifeng']

posted @ 2018-04-29 15:11  夏天的麦田  阅读(890)  评论(0)    收藏  举报