如何在python中的字典列表中进行插入排序? [英] How to do an insertion sort on a list of dictionaries in python?
本文介绍了如何在python中的字典列表中进行插入排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
def insertionsort(alldata,key):
for i in alldata:
temp = alldata [i ]
j = i
while j> 0和alldata [i ['key']]< alldata [j - 1 ['key']]:#不知道如何把这个
alldata [j] = alldata [j-1]
alldata [j] = temp
解决方案
我['key']
看起来像错误。您没有在这里使用您的键
变量。
尝试 alldata [i] [键]< alldata [j-1] [key]
作为条件
此外,您还需要更改 j
在你的while循环中,或者它可以永远运行
def insertionsort(alldata,key):
for i在alldata中:
temp = alldata [i]
j = i
while j> 0和alldata [i] [key]< alldata [j - 1] [key]:
alldata [j] = alldata [j - 1]
j - = 1
alldata [j] = temp
I have a list of dictionaries with various keys, all of which are integers, and I need to write a function which uses insertion sort to sort them by the specific key.
def insertionsort(alldata, key):
for i in alldata :
temp = alldata[i]
j = i
while j > 0 and alldata[i['key']] < alldata[j - 1['key']]: # no idea how to put this
alldata[j] = alldata[j-1]
alldata[j] = temp
解决方案
i['key']
looks like mistake. You aren't using your key
variable here.
Try alldata[i][key] < alldata[j - 1][key]
as a condition
Also you need to change j
in your while loop or it can ran forever
def insertionsort(alldata, key):
for i in alldata :
temp = alldata[i]
j = i
while j > 0 and alldata[i][key] < alldata[j - 1][key]:
alldata[j] = alldata[j - 1]
j -= 1
alldata[j] = temp
这篇关于如何在python中的字典列表中进行插入排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文