內置函數:min 用法


內置函數:min 用法

源碼

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

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

基礎用法

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

 

key屬性的使用

當key參數不為空時,就以key的函數對象為判斷的標准。
如果我們想找出一組數中絕對值最小的數,就可以配合lamda先進行處理,再找出最小值

a = [-9, -8, 11, 23, -4, 6]
tes = min(a, key=lambda x: abs(x))
print(tes)

 

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

如果有一組商品,其名稱和價格都存在一個字典中,可以用下面的方法快速找到價格最貴的那組商品:

prices = {
    'A':123,
    'B':450.1,
    'C':12,
    'E':444,
}
# 在對字典進行數據操作的時候,默認只會處理key,而不是value
# 先使用zip把字典的keys和values翻轉過來,再用min取出值最小的那組數據
min_prices = min(zip(prices.values(), prices.keys()))
print(min_prices) # (450.1, 'B')

當字典中的value相同的時候,才會比較key:

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

min_prices = min(zip(prices.values(), prices.keys()))
print(min_prices) # (123, 'B')

min_prices = min(zip(prices.values(), prices.keys()))
print(min_prices) # (123, 'A')

 

 

和max用法基本一致

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM