【问题标题】:Is there a way to sort a list of two element tuples by both elements, but one of the elements reverse sorted?有没有办法按两个元素对两个元素元组的列表进行排序,但其中一个元素是反向排序的?
【发布时间】:2020-01-29 04:17:40
【问题描述】:

我想对元组列表进行排序(元组的格式为 (integer, string)),以便从最大到最小整数对它们进行排序,然后按字母顺序对字符串进行排序,而不会丢失整数顺序。

### Inputs: data = [(86, 'william'), (74, 'olivia'), (86, 'willaim'), (62, 'lyli'), (74, 'olivai'), (62, 'lily')]
### Outputs: data = [(86, 'willaim'), (86, 'william'), (74, 'olivai'), (74, 'olivia'), (62, 'lily'), (62, 'lyli')]
### What I know how to do: I know how to sort the tuples by specific element from greatest to least
import operator
data.sort(key = operator.itemgetter(0), reverse = True)
### This returns:
### data = [(86, 'william'), (86, 'willaim'), (74, 'olivia'), (74, 'olivai'), (62, 'lily'), (62, 'lyli')]
### At this point I'm not sure how to keep the integers ordered while sorting the strings alphabetically

【问题讨论】:

标签: python sorting tuples


【解决方案1】:
data.sort(key=lambda x: (-x[0], x[1]))

如果你的key是一个元组,排序算法会按照元组的第一个元素优先排序,然后是第二个,以此类推。

【讨论】:

    【解决方案2】:

    Python的sortis stable

    sort() 方法保证是稳定的。一个排序是稳定的,如果它保证不改变比较相等的元素的相对顺序——这有助于多次排序(例如,按部门排序,然后按薪级排序)。

    所以你可以先按字符串排序,然后按整数排序。这使整数按降序排列,但任何具有相同整数的项目将保持与按字符串排序时相同的相对顺序。

    from operator import itemgetter
    
    data.sort(key=itemgetter(1))
    data.sort(key=itemgetter(0), reverse=True)
    

    这不如 Mikhail Genkin 的回答那么有效,但它更接近你想要做的事情。

    【讨论】:

      猜你喜欢
      • 2023-04-05
      • 1970-01-01
      • 2022-08-18
      • 2012-03-11
      • 1970-01-01
      • 2012-03-08
      • 2017-01-07
      • 2015-08-28
      • 2020-08-02
      相关资源
      最近更新 更多