Search code examples
pythonsortingzipcriteria

Sorting a Python ZIP using two criteria?


I have an input of two lists: name and age. I want to primarily sort by age (descending), but if there are duplicates of ages, I want to sort those specific duplicate people alphabetically. For example:

name_list = ['Barbara', 'Anna', 'Chloe', 'Debora']
age_list = [31, 31, 45, 50]

Output should be:

['Debora', 'Chloe', 'Anna', 'Barbara'], [50, 45, 31, 31]

I have tried using zip() and .sort(reverse=True). How should I approach this?


Solution

  • After zipping your two lists (name_age = list(zip(name_list, age_list))), your can simply sort first: name_age.sort(). This will sort using the first entry, i.e. alphabetically. Since .sort() implements a stable sort, this order will be kept in case of identical criteria for the next sort. This will guarantee, that the alphabetical order will stay intact for people of the same age.

    If you now sort using the second entry as key: name_age.sort(key=lambda x: x[1], reverse=True), you come up with your desired result. To get the two lists separated again, you can use list comprehensions: [x[0] for x in name_age] and [x[1] for x in name_age].