Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k points)

I'm solving a challenge and have this list of students with scores:

arr = [['E', 21.0], ['A', 20.0], ['B', 20.0], ['C', 19.0], ['D', 19.0]]

I would like the students that have scored the second highest to have their data stored in a second list  fin_arr. If there is only one student, then store only that data. Which means that the above list should return:

print(fin_arr)

[['A', 20.0],

 ['B', 20.0]]

My solution works but that only applies to specific indexes where one can assume that the second highest scores are found at 2nd last and 3rd last indexes (the list has to be not more than 5 entries). But what if the list is a sorted list like the above? I found several ways to evaluate lists but haven't come across specifically checking for equality for indexes within subindexes and I'm lost in my IDE's history of commands. What could be the best way to achieve this?

1 Answer

0 votes
by (25.1k points)

You can do this by using list comprehensions along with np.unique and np.sort, like this:

import numpy as np

 arr = [['E', 21.0], ['A', 20.0], ['B', 20.0], ['C', 19.0], ['D', 19.0]] second_best_grade = np.sort(np.unique([x[1] for x in arr]))[-2] 

result = [x[0] for x in arr if x[1] == second_best_grade]

Related questions

0 votes
1 answer
0 votes
2 answers
0 votes
1 answer

Browse Categories

...