python - 如何在字典上应用排序算法?
问题描述
我有一本字典d
:
d = {3: 'a', 5: 'g', 1: 't', 4: 'y'}
我想对其进行排序,结果是:
d = {1: 't', 3: 'a', 4: 'y', 5: 'g'}
为了得到这个结果,我需要在列表上应用一个排序算法,比如插入排序或选择排序。如何实施?
解决方案
你想通过键对你的 dict 进行排序。如果我理解你,你想用你选择的排序算法(不是内置算法)对它们进行排序。
所以你应该:
- 实现你的排序算法
- 将其应用于 dict 键
- 创建按键排序的新字典
伪代码:
d = {3: 'a', 5: 'g', 1: 't', 4: 'y'}
# Get the keys as list
d_keys = list(d.keys()) # [3, 5, 1, 4]
# Here, you implement your sorting algorithm on 'd_keys'
# ...
# At the end, you get 'sorted_keys' ('d_keys' sorted): sorted_keys == [1, 3, 4, 5]
# Here you create the new dictionary: (via dictionary comprehension):
sorted_dict = {k:d[k] for k in sorted_keys}
print(sorted_dict)
输出:
d = {1: 't', 3: 'a', 4: 'y', 5: 'g'}
您将在此处找到 Python 中的插入排序算法实现:Python 插入排序如何工作?
在这里选择排序:Selection Sort Python
但是,如果您要求的是“我可以将自己的算法传递给内置sorted
方法”之类的东西,那么答案是否定的。但是,sorted
允许您选择如何比较元素。您将在此处找到有关此内容的更多信息:https ://docs.python.org/3/howto/sorting.html并使用自定义比较函数对列表列表进行排序以及如何在 Python 3 中使用自定义比较函数?.
推荐阅读
- c - 计算和打印矩阵的对角线之和
- javascript - 如何在 Angular 中使用 addEventListener 和 postMessage?
- php - 如何将日期、时间和值从单选按钮放入数据库
- c# - 逐个像素地动态绘制和显示,有一些延迟
- npm - 如何从 Nexus oss 代理获取依赖于 github 项目的 npm 包
- django - Django 测试 - 发送包含整数的数组数组
- android - 在 android 中使用改造登录
- json - 我如何在 nunjuncks 中乘以数据?
- swift - 为什么不能在swift中将可变参数标记为inout?
- vue.js - Vue Js 2 / Vue-CLI 3 / 托管时显示空白页