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)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: bzoj4034: [HAOI2015]
- 下一篇: 数据特征分析(学习笔记)