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
for循环后的所有内容都应再缩进1次(无论您使用多少空格进行缩进)至于其他问题,我都不知道。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.