zoukankan      html  css  js  c++  java
  • Python基础篇【第2篇】: Python内置函数(一)

    Python内置函数

    lambda

      lambda表达式相当于函数体为单个return语句的普通函数的匿名函数。请注意,lambda语法并没有使用return关键字。开发者可以在任何可以使用函数引用的位置使用lambda表达式。在开发者想要使用一个简单函数作为参数或者返回值时,使用lambda表达式是很方便的。总结:处理简单逻辑,自动返回结果

    语法格式:

    lambda parameters: expression

    就相当于

    def fun(args)
        return expression
    

    并且lambda支持多个参数操作

    func = lambda a,b,**kwargs : a+b
    result = func
    print result

    map/fileter/reduce

    参考:map/reduce

    1. map函数
    map函数会根据提供的函数对指定序列做映射。
    def map(function, sequence, *sequence_1): # real signature unknown; restored from __doc__
        """
        map(function, sequence[, sequence, ...]) -> list
        
        Return a list of the results of applying the function to the items of
        the argument sequence(s).  If more than one sequence is given, the
        function is called with an argument list consisting of the corresponding
        item of each sequence, substituting None for missing values when not all
        sequences have the same length.  If the function is None, return a list of
        the items of the sequence (or a list of tuples if more than one sequence).
        """
        return []
    map函数的定义:
    map(function, sequence[, sequence, ...]) -> list    第一个是函数名称,不用加括号,也可是lambda函数,后边是提供给函数操作的值,可以使多个
    通过定义可以看到,这个函数的第一个参数是一个函数,剩下的参数是一个或多个序列,返回值是一个集合。
    function可以理解为是一个一对一或多对一函数,map的作用是以参数序列中的每一个元素调用function函数,返回包含每次function函数返回值的list。
    例一
    对一个序列中的每个元素进行平方运算:
    map(lambda x: x ** 2, [1, 2, 3, 4, 5])
    返回结果为:
    [1, 4, 9, 16, 25]
    在参数存在多个序列时,会依次以每个序列中相同位置的元素做参数调用function函数。

    例二

    比如要对两个序列中的元素依次求和。
    map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
    map返回的list中第一个元素为,参数序列1的第一个元素加参数序列2中的第一个元素(1 + 2),
    list中的第二个元素为,参数序列1中的第二个元素加参数序列2中的第二个元素(3 + 4),
    依次类推,最后的返回结果为:
    [3, 7, 11, 15, 19]

    例三

    要注意function函数的参数数量,要和map中提供的集合数量相匹配。
    如果集合长度不相等,会以最小长度对所有集合进行截取。[官方解释为用none替代,可是有关数字的操作none替代时会报错。]
    当函数为None时,操作和zip相似:
    map(None, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
    返回结果为:
    [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]
    2. fileter函数

    Python内建的filter()函数用于过滤序列。

    map()类似,filter()也接收一个函数和一个序列。和map()不同的时,filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。

    例如,在一个list中,删掉偶数,只保留奇数,可以这么写:

    def is_odd(n):
        return n % 2 == 1
    
    filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])
    # 结果: [1, 5, 9, 15]

    3. reduce

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

    举例:对一个序列求和,就可以用reduce实现

    >>> def add(x, y):
    ...     return x + y
    ...
    >>> reduce(add, [1, 3, 5, 7, 9])
    25

    4. sorted

    我们需要对List进行排序,Python提供了两个方法
    对给定的List L进行排序,
    方法1.用List的成员函数sort进行排序
    方法2.用built-in函数sorted进行排序(从2.4开始)

    --------------------------------sorted---------------------------------------
    >>> help(sorted)
    Help on built-in function sorted in module __builtin__:
    
    sorted(...)
        sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list
    ---------------------------------sort----------------------------------------
    >>> help(list.sort)
    Help on method_descriptor:
    
    sort(...)
        L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
        cmp(x, y) -> -1, 0, 1
    -----------------------------------------------------------------------------

    iterable:是可迭代类型;
    cmp:用于比较的函数,比较什么由key决定,有默认值,迭代集合中的一项;
    key:用列表元素的某个属性和函数进行作为关键字,有默认值,迭代集合中的一项;
    reverse:排序规则. reverse = True 或者 reverse = False,有默认值。
    返回值:是一个经过排序的可迭代类型,与iterable一样。
     
    注;一般来说,cmp和key可以使用lambda表达式。

    sort()与sorted()的不同在于,sort是在原位重新排列列表,而sorted()是产生一个新的列表。

    举例:

    Sorting basic:
    >>> print sorted([5, 2, 3, 1, 4])
    [1, 2, 3, 4, 5]
    >>> L = [5, 2, 3, 1, 4]
    >>> L.sort()
    >>> print L
    [1, 2, 3, 4, 5]
    Sorting  cmp:
    >>>L = [('b',2),('a',1),('c',3),('d',4)]
    >>>print sorted(L, cmp=lambda x,y:cmp(x[1],y[1]))
    [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
    
    Sorting  keys:
    >>>L = [('b',2),('a',1),('c',3),('d',4)]
    >>>print sorted(L, key=lambda x:x[1]))
    [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
    Sorting  reverse:
    >>> print sorted([5, 2, 3, 1, 4], reverse=True)
    [5, 4, 3, 2, 1]
    >>> print sorted([5, 2, 3, 1, 4], reverse=False)
    [1, 2, 3, 4, 5]
    注:效率key>cmp(key比cmp快)

    在Sorting Keys中:我们看到,此时排序过的L是仅仅按照第二个关键字来排的,如果我们想用第二个关键字
    排过序后再用第一个关键字进行排序呢?
    >>> L = [('d',2),('a',4),('b',3),('c',2)]
    >>> print sorted(L, key=lambda x:(x[1],x[0]))
    >>>[('c', 2), ('d', 2), ('b', 3), ('a', 4)]
  • 相关阅读:
    日志模块
    模块介绍3
    模块介绍2
    模块介绍
    迭代器
    Python装饰器续/三元表达式/匿名函数
    Python装饰器详解
    LATEX LIAN XI
    BELLMAN 最短路算法
    B阿狸和桃子的游戏
  • 原文地址:https://www.cnblogs.com/sunailong/p/5192129.html
Copyright © 2011-2022 走看看