【问题标题】:Sorting a list in Descending numerical order and if number is the same, sort by Ascending alphabetical in Python按数字降序对列表进行排序,如果数字相同,则在 Python 中按字母升序排序
【发布时间】:2021-12-19 05:17:03
【问题描述】:

我有 2 个列表,我必须在第二个列表中按降序对它们进行排序。

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

我已经通过使用对它们进行了排序

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

因为它们是使用reverse=True 排序的,所以我的结果也是按字母降序排序的

这会产生结果 ['Boris', 'Amanda', 'Chris', 'Charlie'], [55, 43, 35, 35]

有没有办法产生结果 ['Boris', 'Amanda', 'Charlie', 'Chris'], [55, 43, 35, 35]?

【问题讨论】:

  • 这两个列表有什么关系?为什么不单独排序呢? "I have 2 lists where I have to sort them both by descending order in the second list." 没有任何意义。
  • 这与this question 非常相似,并且那里的答案有效。

标签: python list sorting


【解决方案1】:

试试这个:

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

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

这会产生:

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

【讨论】:

  • 我刚刚更新了这个。理解是不必要的,所以我删除了它。
猜你喜欢
  • 2022-01-09
  • 1970-01-01
  • 2019-07-17
  • 1970-01-01
  • 2022-01-24
  • 2015-10-12
  • 2018-01-14
  • 2023-03-24
  • 2015-10-19
相关资源
最近更新 更多