如何索引列表中最高的3个值?

2024-05-19 10:23:07 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有两个清单:

score = [350, 914, 569, 223, 947, 284, 567, 333, 697, 245, 227, 785, 120, 794, 343, 773, 293, 995]
name = [Ryan, Stacy, Jenna, Peter, Sophie, Bryan, Cole, Andrea, Emily, Blake, Mike, Stephan, Rob, Eliza, Heather, Daniel, Elisabeth, Samantha]

我必须找到3个最高的分数,并将这些分数与名单上各自的分数进行比对,这样我就可以有新的名单了

top3score = [947, 995, 914]
top3name = [Sophie, Samantha, Stacy]

我正在考虑索引最高的分数,将它们附加到一个列表中,而不是使用索引来将这些分数与名字相吻合。

我的问题是如何索引列表中最高的3个值? 然后,如何使用索引在名称列表中查找记分者的名称,以便将其追加到top3name列表中?


Tags: name名称列表bryan分数peterscore名单
2条回答

如果你只对前三名感兴趣,有^{}

>>> heapq.nlargest(3, zip(score, name))
[(995, 'Samantha'), (947, 'Sophie'), (914, 'Stacy')]

official doc

heapq.nlargest(n, iterable, key=None)

Return a list with the n largest elements from the dataset defined by iterable. key, if provided, specifies a function of one argument that is used to extract a comparison key from each element in the iterable: key=str.lower Equivalent to: sorted(iterable, key=key, reverse=True)[:n]

性能通知:

The latter two [nlargest and nsmallest] perform best for smaller values of n. For larger values, it is more efficient to use the sorted() function. Also, when n==1, it is more efficient to use the built-in min() and max() functions.

我想这样就行了

sorted(zip(score, name), reverse=True)[:3]

所以你知道发生了什么:

zip:以iterable作为参数,从每个iterable中提取一个元素,将它们放在元组中。

所以:

>>> zip(score, name)
[(350, 'Ryan'), (914, 'Stacy'), (569, 'Jenna'), (223, 'Peter'), (947, 'Sophie'), (284, 'Bryan'), (567, 'Cole'), (333, 'Andrea'), (697, 'Emily'), (245, 'Blake'), (227, 'Mike'), (785, 'Stephan'), (120, 'Rob'), (794, 'Eliza'), (343, 'Heather'), (773, 'Daniel'), (293, 'Elisabeth'), (995, 'Samantha')]

sorted:将对数据进行排序。默认情况下,元组元素按0索引中的元素排序,因此在本例中为得分。Reverse=True将首先按降序排序。

最后,[:3]是切片表示法,表示从头到尾给我所有元素。这也可以写成[0:3]

相关问题 更多 >

    热门问题