python提供了一些有趣且實用的函數,如any all zip,這些函數能夠大幅簡化我們的代碼,可以更優雅的處理可迭代的對象,同時使用的時候也得注意一些情況
any
-
any
( iterable) -
Return True if any element of the iterable is true. If the iterable is empty, return False
(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
(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
.
(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])
>>> for idx, e in enumerate(('a', 'b', 'c'), 1):
... print idx, e
...
1 a
2 b
3 c