#filter()函数用于过滤序列,接收一个函数和一个序列,filter把传入的函数依次作用于每个元素,若返回的是True则保留该元素,否则丢弃该元素
#从序列中删除奇数,保留偶数
def is_even(num):
return num % 2 == 0
print(list(filter(is_even,range(0,11))))
#把序列中的空字符串删掉
def not_empty(s):
return s and s.strip()
print(list(filter(not_empty,['a','b','','c',None,' ',' '])))
#使用Filter函数求素数(仅能被1和自身整除)
L = [2]
def isprime(n):
right = True
global L
for x in L:
if x != n and n % x == 0:
right = False
break
return right
def primes(max):
n = 3
global L
while n < max:
L.append(n)
L = list(filter(isprime,L))
n+=2
print(L)
primes(100)
#使用埃氏筛法计算素数
def _odd_iter():
n = 1
while True:
n = n + 2
yield n
def _not_divisible(n):
return lambda x: x % n > 0
def primes():
yield 2
it = _odd_iter() # 初始序列
while True:
n = next(it) # 返回序列的第一个数
yield n
it = filter(_not_divisible(n), it) # 构造新序列
L=[]
for n in primes():
if n < 1000:
L.append(n)
print(n)
else:
break
#使用Filter函数得到回数列表
def ispalindrome1(n): #笨办法,通过循环将数字的第一位与最后一位进行对比,以此类推,如果有任何一处不相等则不是回数
s = str(n)
x,l = 0,len(s)
right = True
while x < l:
if s[x] != s[-x - 1]:
right = False
break
x+=1
return right
def ispalindrome2(n): #利用字符串的截取方法取字符串的反序列,然后进行对比,简洁明了~~
return str(n) == str(n)[::-1]
def get_palindrome_list(n):
l = filter(ispalindrome1,range(n))
return list(l)
print(get_palindrome_list(100))
Python学习笔记6——Filter
最新推荐文章于 2024-06-20 15:44:55 发布