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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM