How to do an insertion sort on a list of dictionaries in python?

北城余情 提交于 2019-12-24 12:40:31

问题


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

回答1:


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



回答2:


Every thing after the for loop shuld be indented 1 more time (whatever number of spaces you use for indenting) As for any other issues, I dont know.



来源:https://stackoverflow.com/questions/15801027/how-to-do-an-insertion-sort-on-a-list-of-dictionaries-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!