问题
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