迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

在 Python 中获取列表的最大值和最小值的索引

作者:迹忆客 最近更新:2023/12/17 浏览次数:

在本教程中,我们将讨论在 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 中最小值的索引。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Pandas read_csv()函数

发布时间:2024/04/24 浏览次数:254 分类:Python

Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。

Pandas 追加数据到 CSV 中

发布时间:2024/04/24 浏览次数:352 分类:Python

本教程演示了如何在追加模式下使用 to_csv()向现有的 CSV 文件添加数据。

Pandas 多列合并

发布时间:2024/04/24 浏览次数:628 分类:Python

本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。

Pandas loc vs iloc

发布时间:2024/04/24 浏览次数:837 分类:Python

本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便