zoukankan      html  css  js  c++  java
  • python函数式编程

    map

    其中,function 参数表示要传入一个函数,其可以是内置函数、自定义函数或者 lambda 匿名函数;iterable 表示一个或多个可迭代对象,可以是列表、字符串等。
    map() 函数的功能是对可迭代对象中的每个元素,都调用指定的函数,并返回一个 map 对象。

    listDemo = [1, 2, 3, 4, 5]
    new_list = map(lambda x: x * 2, listDemo)
    print(list(new_list))
    

    filter

    filter() 函数的功能是对 iterable 中的每个元素,都使用 function 函数判断,并返回 True 或者 False,最后将返回 True 的元素组成一个新的可遍历的集合。

    listDemo = [1, 2, 3, 4, 5]
    new_list = filter(lambda x: x % 2 == 0, listDemo)
    print(list(new_list))
    

    reduce

    reduce() 函数通常用来对一个集合做一些累积操作,其基本语法格式为:
    reduce(function, iterable)

    import functools
    listDemo = [1, 2, 3, 4, 5]
    product = functools.reduce(lambda x, y: x * y, listDemo)
    print(product)
    

    zip

    >>>a = [1,2,3]
    >>>b = [4,5,6]
    >>>c = [4,5,6,7,8]
    >>>zipped = zip(a,b) # 打包为元组的列表
    [(1, 4), (2, 5), (3, 6)]
    >>>zip(a,c)          # 元素个数与最短的列表一致
    [(1, 4), (2, 5), (3, 6)]
    >>>zip(*zipped)      # 与 zip 相反,可理解为解压,返回二维矩阵式
    [(1, 2, 3), (4, 5, 6)]
    

    sorted

    >>> L=[('b',2),('a',1),('c',3),('d',4)]
    >>> sorted(L, key=lambda x:x[1])               # 利用key
    [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
    
    >>> students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
    >>> sorted(students, key=lambda s: s[2])            # 按年龄排序
    [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
    
  • 相关阅读:
    【SCOI 2011】 糖果
    【POJ 3159】 Candies
    【POJ 1716】 Integer Intervals
    【POJ 2983】 Is the information reliable?
    【POJ 1364】 King
    【POJ 1201】 Intervals
    【POJ 1804】 Brainman
    6月10日省中提高组题解
    【POJ 3352】 Road Construction
    【POJ 1144】 Network
  • 原文地址:https://www.cnblogs.com/changting/p/13720264.html
Copyright © 2011-2022 走看看