网络编程
位置:首页>> 网络编程>> Python编程>> python 找出list中最大或者最小几个数的索引方法

python 找出list中最大或者最小几个数的索引方法

作者:ShawDa  发布时间:2022-08-12 13:23:11 

标签:python,list,索引

如下所示:


nums = [1,8,2,23,7,-4,18,23,24,37,2]
result = map(nums.index, heapq.nlargest(3, nums))
temp=[]
Inf = 0
for i in range(3):
 temp.append(nums.index(max(nums)))
 nums[nums.index(max(nums))]=Inf
result.sort()
temp.sort()
print(result)
print(temp)

如上,有result和temp两种求法,上面代码输出:


[3, 8, 9]
[3, 8, 9]

没问题

但是把nums改一下:


nums = [1,8,2,23,7,-4,18,23,23,37,2]

输出:


[3, 3, 9]
[3, 7, 9]

发现问题了吧,result方法发现相同数字永远会返回第一次出现的索引。

来源:https://blog.csdn.net/sinat_36811967/article/details/79572960

0
投稿

猜你喜欢

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