python奇技淫巧——max/min函數的用法

本文以max()爲例,對min/max內建函數進行說明ide

源碼函數

def max(*args, key=None): # known special case of max
    """
    max(iterable, *[, default=obj, key=func]) -> value
    max(arg1, arg2, *args, *[, key=func]) -> value

    With a single iterable argument, return its biggest item. The
    default keyword-only argument specifies an object to return if
    the provided iterable is empty.
    With two or more arguments, return the largest argument.
    """
    pass

初級技巧

tmp = max(1,2,4)
print(tmp)
#可迭代對象
a = [1, 2, 3, 4, 5, 6]
tmp = max(a)
print(tmp)

中級技巧:key屬性的使用

當key參數不爲空時,就以key的函數對象爲判斷的標準。
若是咱們想找出一組數中絕對值最大的數,就能夠配合lamda先進行處理,再找出最大值code

a = [-9, -8, 1, 3, -4, 6]
tmp = max(a, key=lambda x: abs(x))
print(tmp)

高級技巧:找出字典中值最大的那組數據

若是有一組商品,其名稱和價格都存在一個字典中,能夠用下面的方法快速找到價格最貴的那組商品:對象

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:ip

prices = {
    'A': 123,
    'B': 123,
}

max_prices = max(zip(prices.values(), prices.keys()))
print(max_prices) # (123, 'B')

min_prices = min(zip(prices.values(), prices.keys()))
print(min_prices) # (123, 'A')
相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息