內置函數之max
阿新 • • 發佈:2018-09-04
spa iterable 商品 ide pass 函數 only *args pytho
源碼:
1 def max(*args, key=None): # known special case of max 2 """ 3 max(iterable, *[, default=obj, key=func]) -> value 4 max(arg1, arg2, *args, *[, key=func]) -> value 5 6 With a single iterable argument, return its biggest item. The 7 default keyword-only argument specifies an object to return if8 the provided iterable is empty. 9 With two or more arguments, return the largest argument. 10 """ 11 pass
簡單使用:
ret = max(1, 2, 4) print(ret)
結果:
4
一般使用:
當key不為空時,就以key的函數對象為判斷的標準.
如果我們想找出一組數中絕對值最大的書,就可以配合lambda先進行處理,再找出最大值.
a = [-9, -8, 1, 3, -4, 6] ret = max(a, key=lambda x: abs(x)) print(ret)
結果:
-9
騷操作:找出字典中值最大的那組數據
如果有一組商品,其名稱和價格都存在一個字典中,可以用下面的方法快速找到價格最貴的那組商品:
prices = { ‘A‘: 123, ‘B‘: 450.1, ‘C‘: 12, ‘E‘: 444 } # 在對字典進行數據操作的時候,默認值會處理key,而不是value # 先使用zip把字典的keys和values翻轉過來,再用max取出值最大的那組數據 max_prices = max(zip(prices.values(), prices.keys())) print(max_prices)
結果:
(450.1, ‘B‘)
當字典中的value相同的時候,才會比較key:
prices = { ‘A‘: 123, ‘B‘: 123 } max_prices = max(zip(prices.values(), prices.keys())) print(max_prices) min_prices = min(zip(prices.values(), prices.keys())) print(min_prices)
結果:
(123, ‘B‘) (123, ‘A‘)
dic = { ‘k1‘: 10, ‘k2‘: 100, ‘k3‘: 30 } print(max(dic)) print(dic[max(dic, key= lambda k: dic[k])])
結果:
k3 100
內置函數之max