【问题标题】:how to sort a list of tuples by two items toghether python [duplicate]如何按两个项目对元组列表进行排序python [重复]
【发布时间】:2019-05-15 16:43:54
【问题描述】:

mylist = [('Action',1) , ('Horror',2) , ('Adventure',0) , ('History',2) , ('Romance',1) ,('Comedy',1)]

我有一个这样的元组列表:

Action: 1
Horror: 2
Adventure: 0
History: 2
Romance: 1
Comedy: 1

我想按两个元素(名称(按字母顺序)和值)对此进行排序

我的结果应该是:

History: 2
Horror: 2
Action: 1
Comedy: 1
Romance: 1
Adventure: 0

【问题讨论】:

    标签: sorting


    【解决方案1】:

    以下应该有效:

    from operator import itemgetter
    
    sorted_list = sorted(mylist, key=itemgetter(0,1), reverse=True)
    

    您可以在本文档的“操作员模块功能”部分中阅读有关此方法的更多信息: https://wiki.python.org/moin/HowTo/Sorting/

    【讨论】:

    • 你需要 from operator import itemgetter 但结果不是 OP 想要的
    • 没错,我做了一些更改,但答案仍然不是 OP 想要的。接近但不完美
    • 但是您建议的这段代码不起作用
    【解决方案2】:
    from collections import defaultdict
    
    mylist = [('Action',1) , ('Horror',2) , ('Adventure',0) , ('History',2) , ('Romance',1) ,('Comedy',1)]
    
    category = defaultdict(list)
    
    for item in mylist:
        category[item[1]].append(item[0])
    
    sorted(category.items())
    keylist = category.keys()
    for key in sorted(keylist, reverse = True):
        valuelist = category[key]
        valuelist.sort()
        category[key] = valuelist
        for v in valuelist:
            print(str(v),str(key))
    

    输出如下:

    History 2
    Horror 2
    Action 1
    Comedy 1
    Romance 1
    Adventure 0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      • 2018-09-20
      • 2013-08-11
      • 2012-03-11
      • 2019-07-30
      • 1970-01-01
      • 2012-03-13
      相关资源
      最近更新 更多