-1

I have 2 lists where I have to sort them both by descending order in the second list.

lst1 = ['Chris','Amanda','Boris','Charlie']
lst2 = [35,43,55,35]

I have sorted them by using

lst2, lst1 = (list(t) for t in zip(*sorted(zip(lst2, lst1), reverse=True)))

Because they are sorted using reverse=True my result is sorted by descending alphabetical order as well

This produces the result ['Boris', 'Amanda', 'Chris', 'Charlie'], [55, 43, 35, 35]

is there a way to produce the result ['Boris', 'Amanda', 'Charlie', 'Chris'], [55, 43, 35, 35]?

  • 1
    What do these two lists have to do with each other? Why not sort them individually? `"I have 2 lists where I have to sort them both by descending order in the second list."` doesn't really make any sense. – ddejohn Nov 05 '21 at 03:28
  • 1
    This is very similar to [this question](https://stackoverflow.com/questions/14466068/sort-a-list-of-tuples-by-second-value-reverse-true-and-then-by-key-reverse-fal) and the answers there work. – Bill Nov 05 '21 at 03:53

1 Answers1

0

Try this:

lst1 = ['Chris','Amanda','Boris','Charlie']
lst2 = [35,43,55,35]

lst1, lst2 = zip(*sorted(zip(lst1, lst2), key=lambda p: (-p[1], p[0])))

This produces:

>>> lst1
['Boris', 'Amanda', 'Charlie', 'Chris']
>>> lst2
[55, 43, 35, 35]
>>> 
Tom Karzes
  • 22,815
  • 2
  • 22
  • 41