在 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