How to do an insertion sort on a list of dictionar

2019-07-24 17:36发布

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

2条回答
兄弟一词,经得起流年.
2楼-- · 2019-07-24 18:18

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.

查看更多
够拽才男人
3楼-- · 2019-07-24 18:24

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
查看更多
登录 后发表回答