22-高级特性之内建方法(3)
filter
定義:傳入一個(gè)函數(shù)f與Iterable對(duì)象I,返回一個(gè)Iterator。根據(jù)f(I(i))的返回值是True或False來(lái)決定是否保留I(i)。起到過(guò)濾器的功能
def is_odd(x):
return (x%2 == 1)
L1 = list(filter(is_odd, range(11))) #filter和map類(lèi)似,返回值都是一個(gè)Iterator,是惰性序列{無(wú)窮stream},要用list之類(lèi)的結(jié)構(gòu)解析出來(lái)
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')篩選法選擇素?cái)?shù):
#1.構(gòu)造產(chǎn)生奇數(shù)的gererator:從3開(kāi)始
def create_odd():
n = 1
while True:
n += 2
yield n
#2.構(gòu)造篩選函數(shù)
def is_divisible(n):
return (lambda x: (x%n > 0)) #過(guò)濾掉n的倍數(shù),即x%n==0的數(shù),此時(shí)默認(rèn)x>n; x待會(huì)兒用Iterator傳入即可
#3.構(gòu)造篩選素?cái)?shù)的函數(shù)
def GetPrime():
yield 2 #2作為特殊數(shù)據(jù)直接輸出
it = create_odd() #產(chǎn)生奇數(shù)流,3開(kāi)始
while True:
n = next(it) #下一個(gè)產(chǎn)生的素?cái)?shù)n
yield n
it = filter(is_divisible(n), it) #把剛產(chǎn)生的n,的倍數(shù)都過(guò)濾掉,再次生成"新的it"
#4.調(diào)用100以內(nèi)的is_prime,產(chǎn)生素?cái)?shù)
primes = GetPrime() #當(dāng)然primes作為Iterator,當(dāng)然是Iterable,可以用for迭代
L4 = []
while True:
n = next(primes) #Iterator的特點(diǎn),可以用next逐個(gè)取出
L4.append(n)
if (n >= 97):
break
print(L4,'\n')作業(yè):篩選出回文數(shù)
#print(list(range(10)))
#1.構(gòu)造從0開(kāi)始的generator
def create_num():
n = 0
while True:
yield n
n += 1
#2.構(gòu)造篩選函數(shù)
#逆轉(zhuǎn)一個(gè)整數(shù) print(int((str(123)[-1::-1]))) #先把整數(shù)變成字符串,再用[]進(jìn)行顛倒,最后轉(zhuǎn)化成整數(shù)
def is_palindrome(x):
return (x == int(str(x)[-1::-1])) #x 與其“反數(shù)”是否相等,若等為回文
#print(is_palindrome(123))
#3.構(gòu)造篩選回文數(shù)的函數(shù)
def GetPalindrome():
it = create_num() #創(chuàng)建自然數(shù)集合
it = filter(is_palindrome, it) #對(duì)非回文數(shù)進(jìn)行過(guò)濾
while True:
n = next(it) #逐個(gè)取出并返回
yield n
#4.調(diào)用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')
轉(zhuǎn)載于:https://www.cnblogs.com/LS1314/p/8504483.html
總結(jié)
以上是生活随笔為你收集整理的22-高级特性之内建方法(3)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: bzoj4034: [HAOI2015]
- 下一篇: 数据特征分析(学习笔记)