[英]How to do an insertion sort on a list of dictionaries in python?
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. i['key']
看起来像是错误。 You aren't using your key
variable here. 您不在此处使用key
变量。
Try alldata[i][key] < alldata[j - 1][key]
as a condition 尝试使用alldata[i][key] < alldata[j - 1][key]
作为条件
Also you need to change j
in your while loop or it can ran forever 另外,您需要在while循环中更改j
,否则它可能永远运行
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
for循环后的所有内容都应再缩进1次(无论您使用多少空格进行缩进)至于其他问题,我都不知道。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.