如何在Python中查找列表中的第1,第2,第3最高值

Has*_*eed 7 python arrays list

我知道如何找到第一个最高值,但不知道其余的值.请记住,我需要打印第一个第二和第三个最高值的位置.谢谢你,并试着保持简单,因为我只编码了2个月.他们也可以成为联合队伍

def linearSearch(Fscore_list):
    pos_list = []
    target = (max(Fscore_list))
    for i in range(len(Fscore_list)):
        if Fscore_list[i] >= target:
            pos_list.append(i)


        return pos_list
Run Code Online (Sandbox Code Playgroud)

Sco*_*ter 5

这将打印 3 个最高项目的列表,每个项目与其索引配对:

lst = [9,7,43,2,4,7,8,5,4]
print( sorted( [(x,i) for (i,x) in enumerate(lst)], reverse=True )[:3] )
Run Code Online (Sandbox Code Playgroud)

如果同一个值可以出现多次(这将显示一个值的最高位置),事情会更复杂一些:

lst = [9,7,43,2,4,7,8,5,4]
ranks = sorted( [(x,i) for (i,x) in enumerate(lst)], reverse=True )
values = []
posns = []
for x,i in ranks:
    if x not in values:
        values.append( x )
        posns.append( i )
        if len(values) == 3:
            break
print zip( values, posns )
Run Code Online (Sandbox Code Playgroud)


rob*_*ert 5

使用heapq.nlargest

>>> import heapq
>>> [i
...     for x, i
...     in heapq.nlargest(
...         3,
...         ((x, i) for i, x in enumerate((0,5,8,7,2,4,3,9,1))))]
[7, 2, 3]
Run Code Online (Sandbox Code Playgroud)


jwp*_*fox 2

将列表中的所有值添加到一个集合中。这将确保您只拥有每个值一次。

对集合进行排序。

在原始列表中查找集合中前三个值的索引。

合理?

编辑

thelist = [1, 45, 88, 1, 45, 88, 5, 2, 103, 103, 7, 8]
theset = frozenset(thelist)
theset = sorted(theset, reverse=True)

print('1st = ' + str(theset[0]) + ' at ' + str(thelist.index(theset[0])))
print('2nd = ' + str(theset[1]) + ' at ' + str(thelist.index(theset[1])))
print('3rd = ' + str(theset[2]) + ' at ' + str(thelist.index(theset[2])))
Run Code Online (Sandbox Code Playgroud)

编辑

您还没有告诉我们如何处理“联合获胜者”,但看看您对其他答案的回应,我猜这可能就是您想要做的,也许?如果这不是您想要的输出,请给我们一个您希望获得的输出的示例。

thelist = [1, 45, 88, 1, 45, 88, 5, 2, 103, 103, 7, 8]
theset = frozenset(thelist)
theset = sorted(theset, reverse=True)
thedict = {}
for j in range(3):
    positions = [i for i, x in enumerate(thelist) if x == theset[j]]
    thedict[theset[j]] = positions

print('1st = ' + str(theset[0]) + ' at ' + str(thedict.get(theset[0])))
print('2nd = ' + str(theset[1]) + ' at ' + str(thedict.get(theset[1])))
print('3rd = ' + str(theset[2]) + ' at ' + str(thedict.get(theset[2])))
Run Code Online (Sandbox Code Playgroud)

输出

1st = 103 at [8, 9]
2nd = 88 at [2, 5]
3rd = 45 at [1, 4]
Run Code Online (Sandbox Code Playgroud)

顺便说一句:如果所有值都相同(等于第一)或由于某种其他原因没有第三位怎么办?(或第二名?)。您需要防范这种情况吗?如果您这样做,那么我确信您可以制定适当的安全防护罩以添加到代码中。