日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

22-高级特性之内建方法(3)

發布時間:2025/4/14 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 22-高级特性之内建方法(3) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

filter

  • 定義:傳入一個函數f與Iterable對象I,返回一個Iterator。根據f(I(i))的返回值是True或False來決定是否保留I(i)。起到過濾器的功能

    def is_odd(x):
    return (x%2 == 1)
    L1 = list(filter(is_odd, range(11))) #filter和map類似,返回值都是一個Iterator,是惰性序列{無窮stream},要用list之類的結構解析出來
    print(L1,'\n')

    def ridofempty(s):
    return s and s.strip()
    L2 = ['', 'abc', 'cde', ' ', ' abc', 'cde ']
    L3 = list(filter(ridofempty, L2))
    print(L2,'\n', L3, '\n')

  • 篩選法選擇素數:

    #1.構造產生奇數的gererator:從3開始
    def create_odd():
    n = 1
    while True:
    n += 2
    yield n
    #2.構造篩選函數
    def is_divisible(n):
    return (lambda x: (x%n > 0)) #過濾掉n的倍數,即x%n==0的數,此時默認x>n; x待會兒用Iterator傳入即可
    #3.構造篩選素數的函數
    def GetPrime():
    yield 2 #2作為特殊數據直接輸出
    it = create_odd() #產生奇數流,3開始
    while True:
    n = next(it) #下一個產生的素數n
    yield n
    it = filter(is_divisible(n), it) #把剛產生的n,的倍數都過濾掉,再次生成"新的it"
    #4.調用100以內的is_prime,產生素數
    primes = GetPrime() #當然primes作為Iterator,當然是Iterable,可以用for迭代
    L4 = []
    while True:
    n = next(primes) #Iterator的特點,可以用next逐個取出
    L4.append(n)
    if (n >= 97):
    break
    print(L4,'\n')

  • 作業:篩選出回文數

    #print(list(range(10)))
    #1.構造從0開始的generator
    def create_num():
    n = 0
    while True:
    yield n
    n += 1
    #2.構造篩選函數
    #逆轉一個整數 print(int((str(123)[-1::-1]))) #先把整數變成字符串,再用[]進行顛倒,最后轉化成整數
    def is_palindrome(x):
    return (x == int(str(x)[-1::-1])) #x 與其“反數”是否相等,若等為回文
    #print(is_palindrome(123))
    #3.構造篩選回文數的函數
    def GetPalindrome():
    it = create_num() #創建自然數集合
    it = filter(is_palindrome, it) #對非回文數進行過濾
    while True:
    n = next(it) #逐個取出并返回
    yield n
    #4.調用GetPalindrome
    # ps = GetPalindrome()
    # L5 = []
    # while True:
    # n = next(ps)
    # L5.append(n)
    # if (n >= 1000):
    # break
    # print(L5)
    L5 = []
    for n in GetPalindrome():
    if (n >= 100000):
    break
    L5.append(n)
    print(L5, '\n')

轉載于:https://www.cnblogs.com/LS1314/p/8504483.html

總結

以上是生活随笔為你收集整理的22-高级特性之内建方法(3)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。