0

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?

Franz
  • 357
  • 3
  • 11
  • Does this answer your question? [How to sort two lists based on one first and the other next in Python?](https://stackoverflow.com/questions/63753064/how-to-sort-two-lists-based-on-one-first-and-the-other-next-in-python) – superb rain Sep 07 '20 at 09:47

2 Answers2

0

this is the result of the key: sorted values you just need to replace it into list

'''

name_list = ['Barbara', 'Anna', 'Chloe', 'Debora']
age_list = [31, 31, 45, 50]
example_dict = dict(zip(name_list,age_list))
example_dict = sorted(example_dict.items(), key = lambda x : x[1], reverse = True)

'''
새러엄
  • 41
  • 3
0

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

Franz
  • 357
  • 3
  • 11