1. 程式人生 > 實用技巧 >python 的filter()函式

python 的filter()函式

filter():

map()類似,filter()也接收一個函式和一個序列。和map()不同的是,filter()把傳入的函式依次作用於每個元素,然後根據返回值是True還是False決定保留還是丟棄該元素

#在一個list中,刪掉偶數,只保留奇數,可以這麼寫
def is_odd(n):
    return n%2==1

list(filter(is_odd,[1,2,3,4,5,6,7,8,9]))  #[1, 3, 5, 7, 9]

#把一個序列中的空字串刪掉,可以這麼寫,trip() 方法用於移除字串頭尾指定的字元(預設為空格或換行符)或字元序列
def not_empty(s):
    
return s and s.strip() list(filter(not_empty,['a','',None,'c']))

練習

#回數是指從左向右讀和從右向左讀都是一樣的數,例如12321,909。請利用filter()篩選出回數:

def is_palindrome(n):
    n=str(n)
    l=len(n)
    if l==1:
        return n
    else:
        for i in range(l):
            if n[i]!=n[-i-1]:  #主要這這裡
                break
            return
n output = filter(is_palindrome, range(1, 1000)) print('1~1000:', list(output)) if list(filter(is_palindrome, range(1, 200))) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191]: print('測試成功!') else: print('測試失敗!')