Python學習筆記__4.1.2章 filter

來源:互聯網
上載者:User

標籤:程式設計語言   Python   

# 這是學習廖雪峰老師python教程的學習筆記

1、概覽

Python內建的filter()函數用於過濾序列

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

 

# 在一個list中,刪掉偶數,只保留奇數

def is_odd(n):

    return n % 2 == 1

list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))   #filter()函數返回的是一個Iterator,需要用list()函數獲得所有結果並返回list。

 

# 把一個序列中的Null 字元串刪掉

def not_empty(s):

    return s and s.strip()   # s.strip(chars) ,移除字串頭尾指定的字元(預設為空白格)

list(filter(not_empty, ['A', '', 'B', None, 'C', '  ']))

 

2、例子

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

# -*- coding: utf-8 -*-

 

#方法一

def is_palindrome(n):

    return str(n)[::-1]==str(n)   #str(n)[::-1]  步長是-1,表示從索引-1開始取,每次增加-1。意義為倒序複製

 

#方法二

def is_palindrome(n):

    s= str(n)

    if len(s)>3:

        return s[0]==s[-1] and is_palindrome(int(s[1:-1]))

    else:

        return s[0]==s[-1]

# 測試:

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('測試失敗!')


Python學習筆記__4.1.2章 filter

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.