filter函數用來過濾數據。
1.基本示例:
def is_odd(n):
return n % 2 == 1
newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(f'odd:{newlist}')
print(f'odd:{list(newlist)}')
輸出:
odd:<filter object at 0x10a801978>
odd:[1, 3, 5, 7, 9]
注意:
python3的filter返回時一個迭代器。
2.使用lambda
newlist = filter(lambda x: x % 2 == 1, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
3.filter的func攜帶額外參數
data = [
{'name': 'jim', 'money': 133, 'home': 'ame'},
{'name': 'tom', 'money': 456, 'home': 'chin'}
]
def func(v, a):
if v.get('name') == a:
return True
return False
res = filter(lambda x: func(x, 'tom'), data)
print(f'res:{list(res)}')
定義func的時候,攜帶多個參數,在filter調用時再使用一個lambda來完成額外參數的傳遞。
輸出:
res:[{'name': 'tom', 'money': 456, 'home': 'chin'}]