简体   繁体   中英

how to sort this Nested Data by the number of scores > 90?

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

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]]]

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM