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