i have 2d list implementation as follows. It shows no. of times every student topped in exams:-
JavaScript
x
7
1
list = main_record
2
['student1',1]
3
['student2',1]
4
['student2',2]
5
['student1',5]
6
['student3',3]
7
i have another list of unique students as follows:-
JavaScript
1
3
1
list = students_enrolled
2
['student1','student2','student3']
3
which i want to display student ranking based on their distinctions as follows:-
JavaScript
1
3
1
list = student_ranking
2
['student1','student3','student2']
3
What built in functions can be useful. I could not pose proper query on net. In other words i need python equivalent of following queries:-
JavaScript
1
6
1
select max(main_record[1]) where name = student1 >>> result = 5
2
select max(main_record[1]) where name = student2 >>> result = 2
3
select max(main_record[1]) where name = student3 >>> result = 3
4
5
6
Advertisement
Answer
You define a dict
base key of studentX
and save the max value for each student key
then sort the students_enrolled
base max value of each key.
JavaScript
1
15
15
1
from collections import defaultdict
2
3
main_record = [['student1',1], ['student2',1], ['student2',2], ['student1',5], ['student3',3]]
4
students_enrolled = ['student1','student2','student3']
5
6
# defind dict with negative infinity and update with max in each iteration
7
tmp_dct = defaultdict(lambda: float('-inf'))
8
for lst in main_record:
9
k, v = lst
10
tmp_dct[k] = max(tmp_dct[k], v)
11
print(tmp_dct)
12
13
students_enrolled.sort(key = lambda x: tmp_dct[x], reverse=True)
14
print(students_enrolled)
15
Output:
JavaScript
1
7
1
# tmp_dct =>
2
defaultdict(<function <lambda> at 0x7fd81044b1f0>,
3
{'student1': 5, 'student2': 2, 'student3': 3})
4
5
# students_enrolled after sorting
6
['student1', 'student3', 'student2']
7