zoukankan      html  css  js  c++  java
  • python 的内建函数

    lambda 函数:lambda语句中,冒号前是参数,可以有多个,用逗号隔开,冒号右边的返回值

    1. map/reduce 函数

    (1)map()函数接收两个参数,一个是函数,一个是序列,map将传入的函数依次作用到序列的每个元素,并把结果作为新的list返回

    ''' 将序列中的元素乘方返回 '''
    list = map(lambda x:x*x, [1, 2, 3, 4, 5, 6, 7, 8, 9])
    print list
    ''' 将list所有数字转为字符串 '''
    list = map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9])
    print list

    (2)reduce()函数接收两个参数,一个是函数,一个是序列,将序列中的元素通过一个二元函数处理返回一个结果,reduce把结果继续和序列的下一个元素做累积计算

    ''' 返回所有元素相乘的结果 '''
    result = reduce(lambda x, y: x * y, [1, 2, 3, 4, 5])
    print result

    2. filter 函数:函数接收两个参数,一个是函数,一个是序列,将序列中的元素通过函数过滤后返回一个新的列表

    ''' 返回序列中的偶数 '''
    list = filter(lambda x: x % 2 == 0, [1, 2, 3, 4, 5, 6, 7, 8, 9])
    print list

    3. sorted 函数:函数可以对 list 进行排序,它也可以接收一个比较函数来实现自定义的排序

    ''' 对 list 进行排序 '''
    list = sorted([1, 2, 3, 4, 5, 6, 7, 8, 9], reverse=False)
    print list
    
    ''' 使用自定义函数对 list 进行逆序排序 '''
    def reversed_cmp(x, y):
        if x > y:
            return -1
        if x < y:
            return 1
        return 0
    list = sorted([1, 2, 3, 4, 5, 6, 7, 8, 9], reversed_cmp)
    print list
  • 相关阅读:
    -bash: belts.awk: command not found
    PLS-00357: Table,View Or Sequence reference 'SEQ_TRADE_RECODE.NEXTVAL' not allowed in this context
    初识makefile
    proc:基本数据库操作
    ORA-12154: TNS:could not resolve the connect identifier specified
    简单的爬虫
    合并一个文文件夹下的所有Excel文件
    Python 递归读取文件夹内所有文件名(包含子文件夹)
    CSS
    JQ
  • 原文地址:https://www.cnblogs.com/alenoscar/p/5485859.html
Copyright © 2011-2022 走看看