zoukankan      html  css  js  c++  java
  • py-day4 python filter函数

    filter函数:遍历序列中的每个元素,判断每个元素得到布尔值,如果是True则留下

    #
    例子:条件筛选 name =['m_xiaoli','zhangfei','m_xiaoma','m_wangyun'] ret = [] def test(name): for i in name: if not i.startswith("m"): ret.append(i) return ret print(test(name)) ['zhangfei'] def test1(array): # (最好不要用全局变量,自己定义一个变量如左) for i in array: if not i.startswith("m"): ret.append(i) return ret print(test1(name))

    ['zhangfei']
    # 在写程序时尽量不要把函数写死,
    name =['xiaoli_d','zhangfei','xiaoma_d','m_wangyun']
    ret = []
    def qu_d(n):            # 定义灵活的函数
        return n.endswith('_d')
    def qu_m(w):
        return w.startswith('m_')
    def test(func,array): for i in array: if not func(i): ret.append(i) return ret ret = test(qu_d,name) ref = [] def test2(func2,array2): for p in array2: if not func2(p): ref.append(p) return ref ref = test2(qu_m,name) print('不是_d结尾的:',ret) print('不是m_开头的:',ref) 不是_d结尾的: ['zhangfei', 'm_wangyun'] 不是m_开头的: ['xiaoli_d', 'zhangfei', 'xiaoma_d']
     #不定义,用lamnda函数也可以
    name =['xiaoli_d','zhangfei','xiaoma_d','m_wangyun']
    ret = []
    def test(func,array):
        for i in array:
            if not func(i):
                ret.append(i)
        return ret
    ret = test(lambda i:i.endswith('_d'),name)
    print('不是_d结尾的:', ret)
    
    不是_d结尾的: ['zhangfei', 'm_wangyun']

    # 终极版 filter函数
    name =['xiaoli_d','zhangfei','xiaoma_d','m_wangyun']
    ret = []
    def test(func,array):
        for i in array:
            if not func(i):
                ret.append(i)
        return ret
    ret = filter(lambda i:not i.endswith('_d'),name)
    print('不是_d结尾的:',list(ret))
    
    不是_d结尾的: ['zhangfei', 'm_wangyun']
  • 相关阅读:
    layui 自定义表单验证的几个实例
    elementUI vue upload完整示例
    视频图片--多线程下载工具
    获取邮箱的DNS和MX 工具类
    10大经典排序算法动图演示
    nginx 转将http跳转到https
    Java 导出 Excel 列号数字与字母互相转换工具
    linux 下查看文件个数及大小
    文字不换行的解决办法
    溢出 省略号 ...
  • 原文地址:https://www.cnblogs.com/majunBK/p/10442529.html
Copyright © 2011-2022 走看看