天天看點

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文檔哦~~~