【问题标题】:Python: How do I sort on the second item of a tuple? [duplicate]Python:如何对元组的第二项进行排序? [复制]
【发布时间】:2017-06-16 17:55:39
【问题描述】:

我有这段代码

relations = dict()
relations[('a','b','c')] = 'first'
relations[('a','c','c')] = 'third'
relations[('d','b','c')] = 'second'

relations_sorted = sorted(relations.keys(), key=lambda tup: tup[1])

for key in relations_sorted:
  print( key, relations[key])

这会打印按键元组的第二个元素排序的字典(在 StackOverflow 上找到的解决方案)。

(('d', 'b', 'c'), 'second')
(('a', 'b', 'c'), 'first')
(('a', 'c', 'c'), 'third')

如何将其扩展到对元组中的第二个、第一个、第三个元素的组合进行排序?例如

(('a', 'b', 'c'), 'first')
(('d', 'b', 'c'), 'second')
(('a', 'c', 'c'), 'third')

【问题讨论】:

    标签: python


    【解决方案1】:

    只需使用key=lambda tup: (tup[1], tup[0], tup[2])

    使用operator.itemgetter 甚至更快/更容易/更好:

    from operator import itemgetter
    
    relations_sorted = sorted(relations.keys(), key=itemgetter(1, 0, 2))
    

    【讨论】:

      【解决方案2】:

      更改为key=lambda tup: (tup[1], tup[0], tup[2])

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-05-07
        • 1970-01-01
        • 2012-05-28
        • 1970-01-01
        • 1970-01-01
        • 2019-12-11
        • 2011-02-07
        • 2020-01-14
        相关资源
        最近更新 更多