在 Python 中獲取列表的最大值和最小值的索引
-
在 Python 中使用
max()和list.index()函式獲取列表最大值的索引 -
在 Python 中使用
min()和list.index()函式獲取列表最小值的索引 -
在 Python 中使用
numpy.argmax()函式獲取列表的最大值的索引 -
在 Python 中使用
numpy.argmin()函式獲取列表的最小值的索引
在本教程中,我們將討論在 Python 中獲取列表的最大值和最小值的索引的方法。
在 Python 中使用 max() 和 list.index() 函式獲取列表最大值的索引
max() 函式在 Python 列表中給出最大值。list.index(x) 方法給出列表中 x 的索引。以下程式碼示例向我們展示瞭如何使用 Python 中的 max() 和 list.index() 函式獲取列表最大值的索引。
list1 = [10, 12, 13, 0, 14]
tmp = max(list1)
index = list1.index(tmp)
print(index)
輸出:
4
在上面的程式碼中,我們首先使用 max() 函式獲得列表 list1 內的最大值,並將其儲存在 tmp 中,然後通過將 tmp 傳遞給 list1.index() 方法來獲得最大值的索引。如果我們只想顯示最大值的索引,上述程式碼可以縮短。
list1 = [10, 12, 13, 0, 14]
print(list1.index(max(list1)))
輸出:
4
在 Python 中使用 min() 和 list.index() 函式獲取列表最小值的索引
min() 函式在 Python 列表中給出最小值。上一節已經討論了 list.index(x) 方法。以下程式碼示例向我們展示瞭如何使用 Python 中的 min() 和 list.index() 函式獲取列表的最小值的索引。
list1 = [10, 12, 13, 0, 14]
tmp = min(list1)
index = list1.index(tmp)
print(index)
輸出:
3
在上面的程式碼中,我們首先使用 min() 函式獲得列表 list1 內的最小值,並將其儲存在 tmp 中,然後將 tmp 傳遞給 list1.index() 功能。如果我們只想顯示最小值的索引,上述程式碼可以縮短。
list1 = [10, 12, 13, 0, 14]
print(list1.index(min(list1)))
輸出:
3
在 Python 中使用 numpy.argmax() 函式獲取列表的最大值的索引
NumPy 包中的 numpy.argmax() 函式為我們提供了最大值的索引在列表或陣列中作為引數傳遞給函式的引數。以下程式碼示例向我們展示瞭如何在 Python 中使用 numpy.argmax() 函式獲取列表的最大值的索引。
import numpy
list1 = [10, 12, 13, 0, 14]
maxindex = numpy.argmax(list1)
print(maxindex)
輸出:
4
在上面的程式碼中,我們使用 numpy.argmax() 函式獲得列表 list1 中最大值的索引。
在 Python 中使用 numpy.argmin() 函式獲取列表的最小值的索引
NumPy 包中的 numpy.argmin() 函式為我們提供了列表或陣列作為引數傳遞給函式。以下程式碼示例向我們展示瞭如何在 Python 中使用 numpy.argmin() 函式獲取列表的最小值的索引。
import numpy
list1 = [10, 12, 13, 0, 14]
minindex = numpy.argmin(list1)
print(minindex)
輸出:
3
在上面的程式碼中,我們使用 numpy.argmin() 函式獲得列表 list1 中最小值的索引。
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn