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://zxbcw.cn/post/211827/
- 转载请注明:必须在正文中标注并保留原文链接
- QQ群: PHP高手阵营官方总群(344148542)
- QQ群: Yii2.0开发(304864863)