zoukankan      html  css  js  c++  java
  • python|高级函数|filter|map|reduce|sorted

    filter(func, iterable)

    • 循环调用输入的函数
    • 过滤传入的参数,函数的结果返回的是true那就保存,返回false就不要,且返回的也是迭代器
    • 备注:
      • 迭代器用完一个就扔掉一个,直到全部用完;
      • 可以用list()转化为列表;不转化则返回的为迭代器对象,可以用for循环直接逐个调用
    # superset utils/core.py convert_legacy_filters_into_adhoc()
    for
    filt in filter(lambda x: x is not None, fd[filters]): fd['adhoc_filters'].append(to_adhoc(filt, 'SIMPLE', clause))

    map(func, iterable)|reduce(func, iterable)

    • map将传入的函数,依次作用到序列的每个元素上,并将结果作为新的迭代器返回
    list(map(str, [1,2,3,4,5,6,7,8]))
    • reduce 将函数作用在序列上,该函数必须接受两个参数
    • 每次的计算结果将继续和下一个元素做累计计算
    # 等效写法
    reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)

    # exampl_1
    from functionls import reduce
    def add(x, y):
      return x + y

    reduce(add, [1,3,5,7,9])

    # exampl_2:把序列[1, 3, 5, 7, 9]变换成整数13579
    def fn(x,y):
      return x*10 + y
    reduce(fn, [1,3,5,7,9])

    # exampl_2:字符串str也是一个序列,将str转化为int
    DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
    
    def str2int(s):
        def fn(x, y):
            return x * 10 + y
        def char2num(s):
            return DIGITS[s]
        return reduce(fn, map(char2num, s))

    def char2num(s):
        return DIGITS[s]
    #使用lambda简化内容
    def str2int(s):
        return reduce(lambda x, y: x * 10 + y, map(char2num, s))

    sorted(iterable, key=func)

    • 添加一个key函数,用来自定义排序;key指定的函数作用在list的每一个元素上,并根据返回的结果重新排序
    # 默认升序排列
    sorted([36, 5, -12, 9, -21])
    # 按照绝对值排序
    sorted([36, 5, -12, 9, -21])  

    # 默认按照ASCII的大小排序,‘Z’ < 'a', 所以‘Z’排在前面
    sorted(['bob', 'about', 'Zoo', 'Credit'])
    # 实现忽略大小写的排序方法: 先将字符串全部转化为大写or小写
    sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower)
    # 实现反向排序
    sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True)
    # 实现L的按照名称排序
    L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
    sorted(L, key=lambda x: x[0])
  • 相关阅读:
    时间选择器和日期选择器
    paip.c++ qt 项目工程互相引用的方法
    leetcode_question_85 Largest Rectangle in Histogram
    在VirtualBox虚拟机上采集Fedora15系统
    Oracle
    VC6.0调试大全
    oracle中的exists 和not exists 用法详解
    vi常用命令
    【虚拟化实战】容灾设计之四VPLEX
    CentOS6.3 安装配置 ant
  • 原文地址:https://www.cnblogs.com/bennyjane/p/12696939.html
Copyright © 2011-2022 走看看