【问题标题】:How to sort a dictionary of lists using a sorting algorithm in Python?如何使用 Python 中的排序算法对列表字典进行排序?
【发布时间】:2023-03-22 23:40:02
【问题描述】:

在 Python 中使用排序算法对列表字典进行排序

我正在尝试对列表字典进行排序(降序),而不使用 Python 中存在的固定函数和方法(即 sorted() 和 .sort())

我使用冒泡排序算法创建了一个函数。 但是它正在对元素进行排序,但键并没有与其对应的元素一起移动。

函数如下:

def bubbleDecDic(dictio):
    end=len(dictio)
    ndictio=dictio
    country=list(dictio.keys())
    for i in range(end-1,0,-1):
        for j in range(i):
            if ndictio[country[j]]< ndictio[country[j+1]]:
                ndictio[country[j+1]], ndictio[country[j]]= ndictio[country[j]], ndictio[country[j+1]]
    return ndictio

这是一个输入字典的例子:

swim={'Russia': [0, 1, 1], 'China': [1, 2, 0], 'Australia': [1, 0, 0], 'Cuba': [1, 0, 0], 'Canada': [2, 1, 0]}

# input dictionary
# Country: [ gold, silver, bronze]
# gold > silver > bronze 

{'Russia': [0, 1, 1],
 'China': [1, 2, 0],
 'Australia': [1, 0, 0],
 'Cuba': [1, 0, 0],
 'Canada': [2, 1, 0]}


bubbleDecDic(swim)

输出保持键在同一位置并对元素进行排序:

{'Russia': [2, 1, 0],
 'China': [1, 2, 0],
 'Australia': [1, 0, 0],
 'Cuba': [1, 0, 0],
 'Canada': [0, 1, 1]}

我的目标是按元素排序,但键应该放在一起。

这是我想要得到的输出:

{'Canada': [2, 1, 0],
 'China': [1, 2, 0],
 'Australia': [1, 0, 0],
 'Cuba': [1, 0, 0],
 'Russia': [0, 1, 1]
 }

【问题讨论】:

    标签: python algorithm sorting dictionary


    【解决方案1】:

    基本上,您正在做的是将值重新分配给键。您可以先对键列表进行排序,然后将它们与值一起插入到有序字典中。

    key_list =sorted(d.keys()) # use any function to sort keys 
    d= dict(zip(key_list, [d[i] for i in key_list ]))
    

    【讨论】:

      【解决方案2】:

      Python 字典是根据插入顺序排序的,因此交换字典条目(如列表)可能不是您想要的。相反,我会对键进行排序,然后通过将这些排序后的键与其原始值相关联来创建一个新字典。

      def bubbleDecDic(dictio):
          end = len(dictio)
          countries = list(dictio)
          for i in range(end-1,0,-1):
              for j in range(i):
                  if dictio[countries[j]] < dictio[countries[j + 1]]:
                      countries[j + 1], countries[j] = countries[j], countries[j + 1]
          return {country: dictio[country] for country in countries}
      

      (我没有测试它,但它与您提供的算法基本相同,只是它更改了国家列表而不是dictio。)

      【讨论】:

        猜你喜欢
        • 2015-05-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-22
        • 2021-07-12
        相关资源
        最近更新 更多