• 高阶函数


    高阶函数

    map

    map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回,map的使用方法为==map(func, iterable)==

    l = [1,2,3,4,5]
    L = map(str,l) #isinstance(L,Iterator)-->true
    M = list(L)
    #['1', '2', '3', '4', '5']
    
    ##sample
    def func(x):
        return str(x*x)
    l = [1,2,3,4,5]
    M = map(func, l) #map把运算规则抽象了
    print(list(M))
    

    reduce

    reduce把一个函数作用在一个序列[x1, x2, x3, …]上,这个函数必须接收两个参数==reduce(f, [x1, x2, x3, x4])==,reduce把结果继续和序列的下一个元素做累积计算,其效果就是:==f(f(f(x1, x2), x3), x4)==

    from functools import reduce
    def add(x, y):
        return x + y
    l = [1,1,2,3,5,8]
    R = reduce(add,l)
    #20
    
    • map 和 reduce合用
    ##SAMPLE 1 : change str to int
    from functools import reduce
    def str2int(s):
        def fn(x, y):
            return x * 10 + y
        def char2num(s):
            return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
        # s = ['2','3','7','9','5']
        R = reduce(fn,list(map(char2num, s)))
        return R
    s = '23795'
    print(str2int(s))
    #23795
    
    ##sample 2:
    from functools import reduce
    def str2float(s):
        def char2float(s):
            return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9,'.': -1}[s]
        # s = '123.6'
        flag = 0  # mark the point position
        n = 0
        num = map(char2float, s)
        def n2float(x,y):
            nonlocal flag #nonlocal关键字用来在函数或其他作用域中使用外层(非全局)变量。
            nonlocal n #global关键字用来在函数或其他局部作用域中使用全局变量。但是如果不修改全局变量也可以不使用global关键字
            if y == -1:
                flag = 1
                return x
            if flag == 0:
                return x*10 + y
            else:
                n = n + 1
                flag = flag*10
                return x + y/flag
        return(round(reduce(n2float,num),n))
    
    s = '237.94545'
    print(str2float(s))
    

    filter

    filter()函数用于过滤序列,与map()相似,传入一个函数和一个序列,把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素

    def is_odd(n):
        return n % 大专栏  高阶函数 class="mi">2 == 1
    list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))
    #[1, 5, 9, 15]
    
    
    #sample: check if the number is prime and print the primes < 1000
    def _odd_iter():
        n = 1
        while True:
            n = n + 2
            yield n
    def is_prime(x):
        N = _odd_iter()
        n = 2
        while n:
            n = N.__next__()
            if x % n == 0:
                break
        return n == x #if n<x,x is not a prime,it can be divided into n
    L = _odd_iter()
    s = filter(is_prime,L)
    for i in s:
        if i < 1000:
            print(i)
        else:
            break
    

    sorted

    对序列进行排序可以接收一个key函数(++该函数可以自定义++)来实现自定义的排序,key指定的函数将作用于序列(字符串,列表,字典等)的每一个元素上,并根据key函数返回的结果进行排序;还可以用==reverse==来选择排序的顺序(默认为升序)

    sorted([36, 5, -12, 9, -21], key=abs)
    #[5, 9, -12, -21, 36]
    
    ##sample:
    from operator import itemgetter
    L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
    s = sorted(L,key = str,reverse = False)
    # [('Adam', 92), ('Bart', 66), ('Bob', 75), ('Lisa', 88)]
    print(sorted(L, key=itemgetter(1), reverse=True)) #成绩从高到低
    #[('Adam', 92), ('Lisa', 88), ('Bob', 75), ('Bart', 66)]
    

    Note : ==operator.itemgetter==函数用于获取对象的哪些维的数据

  • 相关阅读:
    poj 2104(线段树)
    poj 1962(并查集+带权更新)
    hdu 2818(并查集,带权更新)
    hdu 1856
    hdu 3172
    hdu 1325(并查集)
    hdu 5023
    pku 2777(经典线段树染色问题)
    hdu 1671(字典树判断前缀)
    hdu 1247 (字典树入门)
  • 原文地址:https://www.cnblogs.com/lijianming180/p/12041290.html
Copyright © 2020-2023  润新知