python求一组数的最大值_python快速求一个数组的最大值/最小值及其索引
enumerate()函數用于將一個可遍歷的數據對象(如列表、元組或字符串)組合為一個索引序列,同時列出數據和數據下標。
x = [3, 2.2, 7.4, 6, 4]
list(enumerate(x))
# 輸出 [(0, 3), (1, 2.2), (2, 7.4), (3, 6), (4, 4)]
operator.itemgetter()函數用于獲取對象的哪些維的數據,參數為想要取的一些維度序號。
x = [3, 2.2, 7.4, 6, 4]
b1 = operator.itemgetter(2, 1)
b1(x) # 輸出 (7.4, 2.2)
b2 = operator.itemgetter(3)
b2(x) # 輸出 6
最后max()函數有一個應用很巧妙的參數key,在這里定義為operator.itemgetter(1),表示對enumerate(x)每個元素的第一維做比較(從0維開始),然后返回第一維值最大的元素,即包含索引和數值。
x = [3, 2.2, 7.4, 6, 4]
min_index, min_number = min(enumerate(x), key=operator.itemgetter(1))
# min_index=1, min_number =2.2
max_index, max_number = max(enumerate(x), key=operator.itemgetter(1))
# max_index=2, max_number = 7.4
還有另一個簡單且low的方法,index()函數返回參數在數組中第一次出現的索引的值,如果數組中不含有這個參數,則拋出異常。
num = [4,1,2,3,4]
max = max(num)
max_index = num.index(max)
#max_index=0
借鑒于:https://blog.csdn.net/qq_15056979/article/details/89194723
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的python求一组数的最大值_python快速求一个数组的最大值/最小值及其索引的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 股权转让备案登记(股权转让备案)
- 下一篇: python中什么叫合法的标识_pyth