我正在为我的大学论文构建一个Python程序,我正在尝试找到一种方法从带有 float 的列表中找到前3个最大数字,这样我就可以将它们的位置保留在另一个列表中以供将来处理。
`maxim=max(listScore)
`i=0
`keep = [-1]*num
`for x in range(0,num):
````if listaScore[x]==maxim:
`````````keep[i]=x
`````````i+=1
`````````listScore[x]=-100
````maxim=max(listaScore)
the results i want is :
listScore=[0.25, 0.5, 0.5, -0.25, -0.25, 0.25]
positions=[1,2,5,-1,-1,-1]
最佳答案
这是一种使用列表理解的方法。这个想法是sort
与列表长度相同的 range
,指定我们要从 key
参数中的列表中获取元素。我们得到的是排序后的范围
,以返回对列表进行排序的索引:
l= [0.25, 0.5, 0.5, -0.25, -0.25, 0.25]
out = [i for i in sorted(range(len(l)), key=l.__getitem__, reverse=True)][:3]
# [1, 2, 0]
如果您想要额外的-1s
:
out + [-1] * (len(l) - len(out))
# [1, 2, 0, -1, -1, -1]
关于python - 在 Python 中查找列表中的前 3 个最大值并将其位置保留在另一个列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56054985/