python - 带字典的插入排序
问题描述
stock={'meat':100,'fish':50,'bread':70, 'milk':35,'chips':15, 'apple':10,'orange':10, 'rice':10,'honey':10,'lemon':10}
def insertionSort( theSeq ):
n = len( theSeq )
for i in range(1, n):
key = theSeq[i]
pos = i
while pos > 0 and key < theSeq[pos - 1]:
theSeq[pos] = theSeq[pos-1]
pos -= 1
theSeq[pos] = key
print('Input List:', stock)
insertionSort(stock)
print('Sorted List:', stock)
这些是我的代码,我一直在尝试使用插入排序对我的字典进行排序,但我一直遇到这个错误并且不知道该怎么做。
我希望我的输出是一个未排序的字典列表,后跟一个排序字典的列表
我会很感激我能得到的任何帮助提前谢谢你
解决方案
字典不是序列(尽管它们在 Python 3.7+ 中保留了插入顺序)。您可以将其转换为列表:
L = list(stock.items())
insertionSort(L)
print(L)
...但显然你的算法不起作用,因为这是输出:
[('lemon', 10), ('meat', 100), ('meat', 100), ('meat', 100), ('meat', 100), ('meat', 100), ('meat', 100), ('milk', 35), ('orange', 10), ('rice', 10)]
推荐阅读
- c# - Ninject 嵌套构造函数参数
- vue.js - vue-tables-2 过滤从父组件传递的参数
- javascript - 如何获取附近div元素的输入属性值和背景颜色?
- angular - Angular7 在 html 标记中的 img="" 上的字符串内插值抛出“不支持评估引号”
- azure - 设备未报告 IoT Edge 自定义模块
- sharepoint - 如何使用 Jquery 查找当前 sharepoint web 是否从父 web 继承权限
- docker - 多个 docker 过滤器选项是否执行本地 AND 或 OR 操作?
- c# - 为什么要避免直接实例化 CollectionView?
- python - 电子邮件说内容是无,知道为什么吗?
- php - PHP 继承适用于一个实例而不是另一个实例