【问题标题】:Sort dictionary in Python by items inside list按列表中的项目对 Python 中的字典进行排序
【发布时间】:2022-12-16 23:12:42
【问题描述】:

是否可以对这种字典进行排序:

  1. 排名第一
  2. 如果排名相同,则按 other_ranks 列表中的第一个元素排序
  3. 如果 other_ranks 中的第一个元素相同 - 更深入直到列表中的最后一个元素。

    如果这很麻烦,我可以用不同的方式使这本字典结构化。

    {'rank': 6, 'other_ranks': [7, 5]}
    {'rank': 1, 'other_ranks': [7, 11, 6, 2]}
    {'rank': 0, 'other_ranks': [12]}
    {'rank': 1, 'other_ranks': [13, 11, 4, 3]}
    {'rank': 1, 'other_ranks': [14, 12, 6, 5]}
    {'rank': 4, 'other_ranks': [5, 4, 3, 2]}
    {'rank': 0, 'other_ranks': [12]}
    

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    假设有一个列表,您可以执行以下操作:

    from operator import itemgetter
    
    lst = [{'rank': 6, 'other_ranks': [7, 5]},
           {'rank': 1, 'other_ranks': [7, 11, 6, 2]},
           {'rank': 0, 'other_ranks': [12]},
           {'rank': 1, 'other_ranks': [13, 11, 4, 3]},
           {'rank': 1, 'other_ranks': [14, 12, 6, 5]},
           {'rank': 4, 'other_ranks': [5, 4, 3, 2]},
           {'rank': 0, 'other_ranks': [12]}]
    
    
    res = sorted(lst, key=itemgetter("rank", "other_ranks"))
    print(res)
    

    输出

    [{'other_ranks': [12], 'rank': 0},
     {'other_ranks': [12], 'rank': 0},
     {'other_ranks': [7, 11, 6, 2], 'rank': 1},
     {'other_ranks': [13, 11, 4, 3], 'rank': 1},
     {'other_ranks': [14, 12, 6, 5], 'rank': 1},
     {'other_ranks': [5, 4, 3, 2], 'rank': 4},
     {'other_ranks': [7, 5], 'rank': 6}]
    

    这里的关键是列表和元组是按字典顺序比较的,来自文档:

    相同类型的序列也支持比较。尤其是, 元组和列表通过比较字典顺序进行比较 相应的元素。

    【讨论】:

      【解决方案2】:

      这就是所谓的词典比较。 Python 元组实现了这一点。

      dictionaries = [
          {'rank': 6, 'other_ranks': [7, 5]},
          {'rank': 1, 'other_ranks': [7, 11, 6, 2]},
          {'rank': 0, 'other_ranks': [12]},
          {'rank': 1, 'other_ranks': [13, 11, 4, 3]},
          {'rank': 1, 'other_ranks': [14, 12, 6, 5]},
          {'rank': 4, 'other_ranks': [5, 4, 3, 2]},
          {'rank': 0, 'other_ranks': [12]},
      ]
      dictionaries.sort(key=lambda dict_: (dict_['rank'], ) + tuple(dict_['other_ranks']))
      

      【讨论】:

        猜你喜欢
        • 2018-11-27
        • 2021-08-25
        • 2013-03-25
        • 2014-06-10
        • 1970-01-01
        • 2013-04-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多