天天看点

python列表过滤技巧

问题:

有一个列表,a = ['a', 'b', '\n       ', 'c', '\n    ', 'd'],要求一句话输出['a', 'b', 'c', 'd']

一句话:(python3)

list(filter(str.strip, a))

其实就是Python的高阶函数filter

还有其他的高阶函数map,reduce...

map的例子:

def f(x):

    return x * x

print(list(map(f, [-2, 5, -6])))

运行结果:[4, 25, 36]

reduce的例子:

from functools import reduce

def f(x, y):

    return x + y

print(reduce(f, [-2, 5, -6], 100))  

运行结果:97

filter的例子:

def is_odd(x):

    return x % 2 == 1

arr = [1, 4, 6, 7, 9, 12, 17]

print(list(filter(is_odd, arr)))

运行结果:[1, 7, 9, 17]

更多的使用方法查看Python文档哦~~~