您的位置:首页 > 编程语言 > Python开发

python列表过滤技巧

2018-04-06 10:59 295 查看
问题:
有一个列表,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文档哦~~~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息