首页 > 其他 > 详细

Filter函數

时间:2020-03-02 15:50:24      阅读:60      评论:0      收藏:0      [点我收藏+]

1. 函數的作用:

filter函數一般用於過濾序列,過濾掉不符合條件的元素,返回由符合條件元素組成的新列表.也就是列表解析,集合解析,字典解析中提及的過濾元素.

這裡順便說一點題外話,在那篇文章中忘了提及: 列表解析屬於語法糖,編譯器會自動對其優化,但是其簡潔性大大的提高了編程的高效性和可閱讀性.

 

2. 語法(使用方法)

我們可以先看一下Python3的AP是如何描述的:

filter(function, iterable)
Construct an iterator from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.

Note that filter(function, iterable) is equivalent to the generator expression (item for item in iterable if function(item)) if function is not None and (item for item in iterable if item) if function is None.

翻譯一下就是如下:

  • filter接收兩個參數,第一個參數為一個函數(過濾元素的規則),第二個元素為需要過濾的序列(列表,字典,集合)
  • function除了是普通的函數還可以是lambda表達式
  • 返回值是迭代器對象(python2.7返回列表)

3. 實際效果:

# 構建一個隨機列表
lis = [randint(0,10) for _ in range(10)]
print(lis) #輸出為[2, 9, 3, 5, 6, 9, 6, 10, 9, 5]
# 使用filter函數進行賽選其中的奇數元素
g = filter(lambda x: x & 1 != 0,lis)
print(g)    # 輸出為 <filter object at 0x000001551904BA88>
# 使用返回的迭代器生成列表
res = list(g)
print(res)    #輸出為[9, 3, 5, 9, 9, 5]

這裡就使用的是lambda表達式,因為這樣很簡潔,能夠實現大部分需求,不是lambda表達式也可以,如下:

lis = [randint(0,10) for _ in range(10)]
print(lis) # [3, 3, 4, 8, 3, 4, 5, 1, 0, 0]

# 判斷是否為奇數
def isOdd(x):
    return x & 1

res = list(filter(isOdd, lis))
print(res) #[3, 3, 3, 5, 1]

這裡我自己定義的函數寫得很簡單,你也可以將其寫得很複雜,

Filter函數

原文:https://www.cnblogs.com/ltozvxe/p/12395948.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!