22-高级特性之内建方法(3)
filter
定義:傳入一個函數(shù)f與Iterable對象I,返回一個Iterator。根據(jù)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')篩選法選擇素數(shù):
#1.構造產生奇數(shù)的gererator:從3開始
def create_odd():
n = 1
while True:
n += 2
yield n
#2.構造篩選函數(shù)
def is_divisible(n):
return (lambda x: (x%n > 0)) #過濾掉n的倍數(shù),即x%n==0的數(shù),此時默認x>n; x待會兒用Iterator傳入即可
#3.構造篩選素數(shù)的函數(shù)
def GetPrime():
yield 2 #2作為特殊數(shù)據(jù)直接輸出
it = create_odd() #產生奇數(shù)流,3開始
while True:
n = next(it) #下一個產生的素數(shù)n
yield n
it = filter(is_divisible(n), it) #把剛產生的n,的倍數(shù)都過濾掉,再次生成"新的it"
#4.調用100以內的is_prime,產生素數(shù)
primes = GetPrime() #當然primes作為Iterator,當然是Iterable,可以用for迭代
L4 = []
while True:
n = next(primes) #Iterator的特點,可以用next逐個取出
L4.append(n)
if (n >= 97):
break
print(L4,'\n')作業(yè):篩選出回文數(shù)
#print(list(range(10)))
#1.構造從0開始的generator
def create_num():
n = 0
while True:
yield n
n += 1
#2.構造篩選函數(shù)
#逆轉一個整數(shù) print(int((str(123)[-1::-1]))) #先把整數(shù)變成字符串,再用[]進行顛倒,最后轉化成整數(shù)
def is_palindrome(x):
return (x == int(str(x)[-1::-1])) #x 與其“反數(shù)”是否相等,若等為回文
#print(is_palindrome(123))
#3.構造篩選回文數(shù)的函數(shù)
def GetPalindrome():
it = create_num() #創(chuàng)建自然數(shù)集合
it = filter(is_palindrome, it) #對非回文數(shù)進行過濾
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]
- 下一篇: SQL优化(二)-- 慢查询