网络编程
位置:首页>> 网络编程>> Python编程>> Python中的min及返回最小值索引的操作

Python中的min及返回最小值索引的操作

作者:su_bao  发布时间:2023-09-24 08:48:19 

标签:Python,min,最小值,索引

1、Python的min函数返回列表中的最小的项。

2、如何返回列表中最小的项的索引?


def indexofMin(arr):
   minindex = 0
   currentindex = 1
   while currentindex < len(arr):
       if arr[currentindex] < arr[minindex]:
           minindex = currentindex
       currentindex += 1
   return minindex
arr = [3,5,2,1]
print(indexofMin(arr))

补充:python返回列表中的最大值(最小值)与其索引

1. 返回列表最大值

使用方法:max()

其语法:该函数返回给定参数的最大值,参数可以为序列。


n = max(list) #list 表示要返回最大值的列表。

结果:返回列表元素中的最大值


list1 = [123, 456, 789]
list2 = ['123', '456', '789']
list3 = ['abc', 'abb', 'acb']

print(max(list1))  #789
print(max(list2))  #789
print(max(list3))  #acb

2. 返回列表最大值的索引

使用方法:利用max找到列表中的最大值,

利用再index()找到最大值的索引

该函数返回给定参数索引,参数为序列中的一个元素。


list1.index(max(list1))

结果返回参数在列表中的索引


list1 = [123, 456, 789]
print(list1.index(456))  #1
print(list1.index(max(list1))) #2

最小值只需要将max换成min即可

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。如有错误或未考虑完全的地方,望不吝赐教。

来源:https://blog.csdn.net/su_bao/article/details/81050960

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com