目錄
一.filter函數簡介
filter函數主要用來篩選數據,過濾掉不符合條件的元素,並返回一個迭代器對象,如果要轉換爲列表list或者元祖tuple,可以使用內置函數list() 或者內置函數tuple()來轉換;
filter函數接收兩個參數,第一個爲函數,第二個爲序列,序列的每個元素作爲參數傳遞給函數進行判,然後返回 True 或 False,最後將返回 True 的元素放到新列表中,就好比是用篩子,篩選指定的元素;
語法:
filter(function, iterable)
參數:
function – 函數名;
iterable – 序列或者可迭代對象;
返回值:通過function過濾後,將返回True的元素保存在迭代器對象中,最後返回這個迭代器對象(python2.0x版本是直接返回列表list);
二.filter函數使用
1.filter函數簡單使用
# !usr/bin/env python
# -*- coding:utf-8 _*-
"""
@Author:何以解憂
@Blog(個人博客地址): shuopython.com
@WeChat Official Account(微信公衆號):猿說python
@Github:www.github.com
@File:python_process_Pool.py
@Time:2020/1/14 21:25
@Motto:不積跬步無以至千里,不積小流無以成江海,程序人生的精彩需要堅持不懈地積累!
"""
def check(i):
# 如果是偶數返回 True 否則返回False
return True if i%2 == 0 else False
if __name__ == "__main__":
list1 =[1,2,3,4,5,6]
result = filter(check,list1)
print(result)
print(type(result))
# 將返回的迭代器轉爲列表list或者元組
print(list(result))
print(type(list(result)))
輸出結果:
<filter object at 0x0000015127BA7EB8>
<class 'filter'>
[2, 4, 6]
<class 'list'>
2.filter函數配合匿名函數Lambda使用
def check_score(score):
if score > 60:
return True
else:
return False
if __name__ == "__main__":
# 成績列表
student_score = {"zhangsan":98,"lisi":58,"wangwu":67,"laowang":99,"xiaoxia":57}
# 篩選成績大於60的成績列表
result = filter(lambda score:score > 60,student_score.values())
# 與上面一行代碼等價
# result = filter(check_score, student_score.values())
print(result)
print(type(result))
# 將返回的迭代器轉爲列表list或者元組
print(list(result))
print(type(list(result)))
輸出結果:
<filter object at 0x000001B761F88FD0>
<class 'filter'>
[98, 67, 99]
<class 'list'>
注意:filter函數返回的是一個迭代器對象,往往在使用時需要先將其轉換爲列表list或者元祖tuple之後再操作;
python filter函數其實和內置函數map()使用方法類似,map()函數也是將迭代器或者序列中的每一個元素映射到指定的函數中,操作完成之後再返回修改後的迭代器對象;
猜你喜歡:
3.python 函數不定長參數*argc,**kargcs
轉載請註明:猿說Python » python filter函數
技術交流、商務合作請直接聯繫博主
掃碼或搜索:猿說python
猿說python
微信公衆號 掃一掃關注