zoukankan      html  css  js  c++  java
  • python 的filter()函数

    filter():

    map()类似,filter()也接收一个函数和一个序列。和map()不同的是,filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素

    #在一个list中,删掉偶数,只保留奇数,可以这么写
    def is_odd(n):
        return n%2==1
    
    list(filter(is_odd,[1,2,3,4,5,6,7,8,9]))  #[1, 3, 5, 7, 9]
    
    #把一个序列中的空字符串删掉,可以这么写,trip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列
    def not_empty(s):
        return s and s.strip()
    
    list(filter(not_empty,['a','',None,'c']))

    练习

    #回数是指从左向右读和从右向左读都是一样的数,例如12321,909。请利用filter()筛选出回数:
    
    def is_palindrome(n):
        n=str(n)
        l=len(n)
        if l==1:
            return n
        else:
            for i in range(l):
                if n[i]!=n[-i-1]:  #主要这这里
                    break
                return n
    
    
    output = filter(is_palindrome, range(1, 1000))
    print('1~1000:', list(output))
    if list(filter(is_palindrome, range(1, 200))) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191]:
        print('测试成功!')
    else:
        print('测试失败!')
  • 相关阅读:
    Iterable,Iterator和forEach
    集合的线程安全性
    Servlet生命周期
    JavaWeb应用的生命周期
    将博客搬至CSDN
    (五)新类库的构件
    Python input和print函数
    python----调试
    Excel决定吃什么
    MATLAB—地图
  • 原文地址:https://www.cnblogs.com/cgmcoding/p/13298831.html
Copyright © 2011-2022 走看看