0

Given a nested list representing gradebooks of different courses:

gradebooks = [[['Troy', 92], ['Alice', 95]], [['James', 89], ['Charles', 100], ['Bryn', 59]]]
  • Using the builtin sorted() function, write code to sort courses by course mean. The expected output is
[[['James', 89], ['Charles', 100], ['Bryn', 59]], [['Troy', 92], ['Alice', 95]]]
  • Using the builtin sorted() function, write code to sort students of each course by score in descending order. The expected output is
[[['Alice', 95], ['Troy', 92]], [['Charles', 100], ['James', 89], ['Bryn', 59]]]

I'm having trouble with these questions, I tried to answer the first question using codes below but it doesnt work.

sort1 = sorted(gradebooks, key=lambda x : sum(gradebooks[x]) / len(gradebooks[x]))

2 Answers 2

1

First, the reason your code does not work is:

sort1 = sorted(gradebooks, key=lambda x : sum(gradebooks[x]) / len(gradebooks[x]))

The parameter key of sorted function is a function that takes a list element as arguments. So x would be [['Troy', 92], ['Alice', 95]] or [['Charles', 100], ['James', 89], ['Bryn', 59]]. Therefore, gradebooks[x] will cause error:

TypeError: list indices must be integers or slices, not list

For the first problem, your lambda function should be:

sort1 = sorted(gradebooks, key=lambda x: sum([grade for _, grade in x]) / len(x))

For the second problem, my thoughts are: overall it is a list comprehension, in the list comprehension, use sorted function to process each element.

sort2 = [sorted(course, key=lambda x: x[1], reverse=True) for course in gradebooks]
Sign up to request clarification or add additional context in comments.

Comments

0

Use:

# sort courses by course mean
sort1 = sorted(gradebooks, key=lambda s: sum(dict(s).values()) / len(s))

# sort students of each course by score in descending order. 
sort2 = list(map(lambda s: sorted(s, reverse=True, key=lambda y: y[1]),  gradebooks))

print(sort1)
print(sort2)

This prints:

[[['James', 89], ['Charles', 100], ['Bryn', 59]], [['Troy', 92], ['Alice', 95]]]
[[['Alice', 95], ['Troy', 92]], [['Charles', 100], ['James', 89], ['Bryn', 59]]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.