[英]Sorting a list in Descending numerical order and if number is the same, sort by Ascending alphabetical in Python
I have 2 lists where I have to sort them both by descending order in the second list.我有 2 个列表,我必须在第二个列表中按降序对它们进行排序。
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因为它们是使用
reverse=True
排序的,所以我的结果也按字母顺序降序排序
This produces the result ['Boris', 'Amanda', 'Chris', 'Charlie'], [55, 43, 35, 35]
这会产生结果
['Boris', 'Amanda', 'Chris', 'Charlie'], [55, 43, 35, 35]
is there a way to produce the result ['Boris', 'Amanda', 'Charlie', 'Chris'], [55, 43, 35, 35]
?有没有办法产生结果
['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]
>>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.