优雅的Python-内置函数

一、sum

Return the sum of a sequence of numbers (NOT strings) plus the value of parameter 'start' (which defaults to 0). When the sequence is empty, return start.

lst = [1, 2, 3, 4, 5]
print sum(lst)  #15

二、all

Return True if bool(x) is True for all values x in the iterable.
If the iterable is empty, return True.

a= [1, 2, 3, 4, 5]
print all(a)  # True
b = [0, 1, 2, 3, 4]
print all(a) # False

三、any

Return True if bool(x) is True for any x in the iterable.
If the iterable is empty, return False.

a = [0, 1,  2]
print any(a)  # True
b = [0, 0, 0]
print any(a) # False

四、enumerate

Return an enumerate object. iterable must be another object that supports iteration. The enumerate object yields pairs containing a count (from start, which defaults to zero) and a value yielded by the iterable argument. enumerate is useful for obtaining an indexed list:
(0, seq[0]), (1, seq[1]), (2, seq[2]), ...

a = ['Coco', 'Andy', 'Mary']
for ind, name in enumerate(a):
    print ind, name
0 Coco
1 Andy
2 Mary

五、zip

Return a list of tuples, where each tuple contains the i-th element
from each of the argument sequences. The returned list is truncated
in length to the length of the shortest argument sequence.

a = (1, 2, 3, 4)
b = (5, 6, 7,)
c = (8, 9, 10)
print zip(a, b, c)
[(1, 5, 8), (2, 6, 9), (3, 7, 10)]

五、map

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).

a = (1, 2, 3)
b = (4, 5, 6)
c = (7, 8, 9)

print map(lambda x: x + 10, a)
print map(lambda x, y, z : x*100 + y * 10 + z, a, b, c)
[11, 12, 13]
[147, 258, 369]

六、 filter

Return those items of sequence for which function(item) is true. If
function is None, return the items that are true. If sequence is a tuple or string, return the same type, else return a list.

a = [1, 2, 3, 4]
b= [1, {}, (), False]
print filter(lambda x: x > 1, a)
print filter(None, b)
[2, 3, 4]
[1,]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容