gradebooks_a = [[['Alice', 95], ['Troy', 92]],
[['Charles', 100], ['James', 89], ['Bryn', 59]],
[['Karren', 97], ['Nancy', 96], ['Astha', 92], ['Jack', 74]]]
How to sort this Nested Data by the number of scores > 90? Thank you.
expected output like this:
[[['Charles', 100], ['James', 89], ['Bryn', 59]], # only 1 score above 90
[['Alice', 95], ['Troy', 92]], # 2 scores above 90
[['Karren', 97], ['Nancy', 96], ['Astha', 92], ['Jack', 74]]] # 3 score above 90
CodePudding user response:
You can use a custom function as key
for sorted
:
out = sorted(gradebooks_a, key=lambda lst: sum([e[1]>90 for e in lst]))
explanation:
For each sublist, identify elements where the second item is greater than 90 and count them using sum
.
output:
[[['Charles', 100], ['James', 89], ['Bryn', 59]],
[['Alice', 95], ['Troy', 92]],
[['Karren', 97], ['Nancy', 96], ['Astha', 92], ['Jack', 74]]]
CodePudding user response:
Use sorted
with a key
function that receives each list of (student, grade)
pairs and sorts according to the number of grades that are > 90
:
sorted(gradebooks_a, key=lambda grades_list: sum(grade > 90
for _, grade in grades_list))
We use unpacking while iterating (for _, grade
) to get a bit more readable code (by giving the second element the name "grade") instead of using indexes. We could use the even more explicit for student, grade
but that would trigger some linters for not using the student
variable.