59. Sort by age, then name
Write a function sort_people(people) that takes a list of people, each a pair [name, age], and returns a new
list of the same pairs in this order:
- the oldest first, down to the youngest;
- people of the same age by name, from A to Z.
Two people can share a name, or a name and an age: keep them all.
Sorting by age alone isn't enough, and neither is reversing a sort by age and name: that would put the names from Z to A as well.
Example 1
people = [["Ann", 30], ["Bob", 25], ["Cy", 30]][["Ann", 30], ["Cy", 30], ["Bob", 25]]Example 2
people = [["Zoe", 20], ["Al", 20]][["Al", 20], ["Zoe", 20]]Example 3
people = [][]Constraints
peoplehas 0 to 50 pairs.- A name is 1 to 20 letters, starting with a capital; an age is a whole number from 0 to 120.
Submit also runs 6 more tests you can't see.
Practises Lambda, map and filter (lesson 19).
sorted(people, key=...)sorts by whatever the key function returns for each item, such aslambda p: p[1]for the age.- Tuples compare item by item, so a key returning
(age, name)sorts by age and then by name for equal ages. - To put the oldest first but keep names A to Z, flip only the age: the key
(-p[1], p[0]).reverse=Truewould flip the names too.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
def sort_people(people):
"""Sort people oldest first, then by name.
people: list of [name, age] pairs (str, int)
Returns: list of the same pairs, by age from oldest,
same ages by name from A to Z
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.