内置函数_最值与求和
最值与求和
-
max()、min()、sum()分别用来计算列表、元组、或其他包含有限个元素的可迭代对象中所有元素最大值、最小值以及所有元素之和
>>> from random import randint
>>> a = [randint(1,100) for i in range(10)]
>>> print(max(a),min(a),sum(a))
92 1 433
>>> a = [randint(1,100) for i in range(10)]
>>> print(max(a),min(a),sum(a))
97 2 471
>>> sum(a)/len(a)
47.1 -
函数max()、min()还支持default参数和key参数
-
default参数用来指定可迭代对象为空时默认返回的最大值或最小值
-
key参数用来指定比较大小的依据或规则,可以是函数或lambda表达式
>>> max(['2','111']) # 不指定排序规则
'2'
>>> max(['2','111'], key = len) # 指定排序规则,返回最长的字符串
'111'
>>> print(max([1,22,44,23,6], default = None))
44
>>> print(max([], default = None)) # 对空列表求最大值,返回空值None
None
>>> lst = [[randint(1,50) for i in range(5)] for j in range(30)]
>>> lst
[[33, 50, 16, 9, 4], [29, 49, 31, 31, 26], [19, 39, 40, 26, 30], [44, 43, 23, 10, 6], [10, 39, 12, 3, 14], [4, 37, 30, 26, 21], [34, 11, 39, 28, 25], [8, 4, 37, 39, 41], [19, 23, 25, 20, 50], [2, 33, 17, 17, 5], [18, 15, 20, 11, 45], [33, 15, 35, 28, 21], [5, 14, 2, 25, 41], [50, 1, 13, 18, 8], [43, 45, 44, 22, 43], [12, 37, 16, 28, 42], [49, 10, 42, 50, 13], [1, 24, 34, 9, 45], [11, 23, 10, 17, 22], [39, 17, 50, 29, 27], [42, 45, 39, 49, 10], [50, 21, 29, 43, 42], [27, 22, 49, 41, 29], [20, 33, 41, 8, 32], [27, 41, 41, 33, 43], [33, 18, 11, 49, 31], [49, 23, 49, 15, 1], [14, 47, 31, 11, 26], [22, 12, 39, 13, 39], [36, 21, 8, 4, 24]]>>> max(lst,key=sum)[43, 45, 44, 22, 43]>>> max(*lst,key=sum)[43, 45, 44, 22, 43]>>> max(lst,key = lambda x: x[1]) # 所有子列表中第二个元素最大的子列表[33, 50, 16, 9, 4]>>> sum(range(1,11))55>>> sum(range(1,11),5) # 指定start参数为5,等价于5+sum(range(1,11))60>>> sum(2**i for i in range(200))1606938044258990275541962092341162602522202993782792835301375>>> int('1'*200,2)1606938044258990275541962092341162602522202993782792835301375>>> int('1'*200,7)1743639715219059529169816601969468943303198091695038943325023347339187627904043708629063769151560675048844208042091052362343863390613931864691792377889969422439576020000>>> sum(range(101))5050>>> 101*100//25050 -