1. 程式人生 > >python內建函式——filter()函式

python內建函式——filter()函式

filter()函式用於過濾序列,過濾掉不符合條件的元素,返回一個迭代器物件,可以通過list()轉化為列表或者通過for迴圈取值。

filter()函式接收兩個引數,第一個為函式,第二個為可迭代物件。返回序列中能使函式為真的元素的迭代器物件;如果函式為None,則返回序列中值為True的元素。

res = filter(None, [-1, 0, 1, 2, "abc", True, False, None])
print(list(res))  # [-1, 1, 2, 'abc', True]

需要注意的是,在python 3.x 和python 2.x 中,返回結果型別不同。執行如下程式碼:

res = filter(lambda x: x % 2 == 1, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(type(res))
print(res)

在python 2.x 中返回結果為:

<type 'list'>
[1, 3, 5, 7, 9]

在python 3.x 中返回結果為:

<class 'filter'>
<filter object at 0x000001941835D0F0>

可以使用自定義的函式:

def is_odd(n):
	"""過濾出列表中的奇數"""
    return n % 2 == 1


res = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(list(res))  # [1, 3, 5, 7, 9]

通過for遍歷取值只能使用一次:

res = filter(lambda x: x % 2 == 1, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

for i in res:
    pass
print(res)  # <filter object at 0x000002A083A6C0B8>
print(list(res))  # []

filter()函式不只可以對資料進行過濾,還可以對字串進行操作:

# 篩選出列表中以字母 a 開頭的字串
res = filter(lambda x: x.startswith('a'), ['abc', 'adsa', 'Def', 'Abd', ])
print(list(res))  # ['abc', 'adsa']

需要注意的是如果列表中有其他型別的元素,比如int型別的資料,則會報錯,因為int型別的資料沒有startswith屬性:

res = filter(lambda x: x.startswith('a'), [1, 'abc', 'adsa', 'Def', 'Abd', ])
print(list(res))  # AttributeError: 'int' object has no attribute 'startswith'