python的filter基本用法

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'}]

猜你喜欢

转载自www.cnblogs.com/shanchuan/p/12969451.html