• Python 小而美的函数


    python提供了一些有趣且实用的函数,如any all zip,这些函数能够大幅简化我们的代码,可以更优雅的处理可迭代的对象,同时使用的时候也得注意一些情况
     
    any
    any(iterable)

    Return True if any element of the iterable is true. If the iterable is empty, return False

    如果序列中任何一个元素为True,那么any返回True。该函数可以让我们少些一个for循环。有两点需要注意
    (1)如果迭代器为空,返回的是False
    (2)具有短路求值性质,即如果迭代器中某个元素返回True,那么就不会对后面的元素求值。
        笔者曾经犯过这么一个错误
        ret = any(self.calc_and_ret(e) for e in elements)
        def self.calc_and_ret(self, e):
            # do a lot of calc here which effect self
            return True(or False)
        本意是希望对所有的element都计算,然后返回一个结果。但事实上由于短路求值, 可能后面很多的元素都不会再调用calc_and_ret
     
    all
    all(iterable)

    Return True if all elements of the iterable are true (or if the iterable is empty

    当所有元素都为True时,all函数返回True。两点注意
    (1)如果迭代器为空,返回的是True
    (2)具有短路求值性质,即如果迭代器中某个元素返回False,那么就不会对后面的元素求值。
     
    sum
    sum(iterable[, start])

    Sums start and the items of an iterable from left to right and returns the total. start defaults to 0.

    sum用来对迭代器的数值求和,且可以赋予一个初始值(默认为0)。注意
    (1)如果是空的迭代器,返回0
     
    max min
    分别返回可迭代序列的最大值 最小值。注意事项
    (1)如果是空的迭代器,会抛异常(ValueError)
     
    zip
    接受n个序列作为参数,返回tuple的一个列表,第i个tuple由每个序列的第i个元素组成。for example
    >>> zip((1,2,3), ('a', 'b', 'c'))
    [(1, 'a'), (2, 'b'), (3, 'c')]
    >>> zip((1,2,3), ('a', 'b', 'c'), (True, False, True))
    [(1, 'a', True), (2, 'b', False), (3, 'c', True)]
    注意:
    (1)作为参数的序列长度可以不一致,以长度最短的序列为准。for example
    >>> zip((1,2,3), ('a', 'b'))
    [(1, 'a'), (2, 'b')]
    (2)即使参数只有一个序列,返回值也是a list of tuple
    >>> zip((1,2,3))
    [(1,), (2,), (3,)]
     
    itertools.izip
    功能能zip,不过返回值是iterator,而不是list
     
    enumerate
    这个函数大家应该都有使用过,用来返回序列中元素的下标和元素。同时容易被忽略的是:enumerate 还接受一个参数作为下标的开始
    enumerate(sequence[, start=0])
    我们知道在Python以及大多数编程语言中,数组(序列)的下标都是以0开始(lua除外)。但在现实中,比如排行,我们都是说第一名,而不是第0名。所以start=1可能是个好主意。
    >>> for idx, e in enumerate(('a', 'b', 'c'), 1):
    ...     print idx, e
    ...
    1 a
    2 b
    3 c
  • 相关阅读:
    重新整理数据结构与算法—— 斐波那契二分查找法[十四]
    重新整理数据结构与算法—— 插值二分查找法[十三]
    重新整理数据结构与算法—— 二分查找法[十二]
    Tuple和ValueTuple
    安装 php_mongodb.dll的坑
    前端——localStorage详细总结
    前端——Vue.js学习总结一
    数据库SQL语句大全,最常用的SQL语句
    Java——多线程超详细总结
    Java——异常那些事
  • 原文地址:https://www.cnblogs.com/xybaby/p/6259823.html
Copyright © 2020-2023  润新知