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]
?
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]
>>>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.