I'm teaching myself programming.
I would like to know how I could make this Python3 could more flexibile, for example if I wanted to find students with the 3rd lowest grade, or the lowest, or any other value. Based on this piece of code (that it took me awhile to fathom out) I'm not convinced Python is the best tool for this task. It uses the data structure it does because the task brief I was working on requested that I use nested lists.
#! /usr/bin/env python3
# Number of student records to expect
n = int(input())
# Take inp of n student records, store in format [[name, score], [name, score], ...]
students = [[input(), float(input())] for studentrecord in range(n)]
# Sort records by score, ascending. Using float else defaults to lexicographical order.
students.sort(key=lambda studentrecord: float(studentrecord[1]))
# Get the lowest mark achieved
lowest_mark = students[0][1]
# Get ind of second lowest scoring student
ind = 0
while students[ind][1] == lowest_mark:
ind += 1
# Get the second lowest mark achieved
second_lowest_mark = students[ind][1]
second_lowest_scoring_students = []
# Accumulate list of second lowest scoring students.
while students[ind][1] == second_lowest_mark:
second_lowest_scoring_students.append(students[ind][0])
ind += 1
if ind == n: # If iteration reaches the end of the list of records, end.
break
# Sort name/s alphabetically.
second_lowest_scoring_students.sort()
# Send results to stdout.
for student_name in second_lowest_scoring_students:
print(student_name)
pandasis a module you can import to make your life easier in this case. \$\endgroup\$