Python学习笔记6——Filter

#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))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值