[英]How to do an insertion sort on a list of dictionaries in python?
我有一個包含各種鍵的字典列表,所有這些鍵都是整數,我需要編寫一個函數,該函數使用插入排序對特定鍵進行排序。
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']
看起來像是錯誤。 您不在此處使用key
變量。
嘗試使用alldata[i][key] < alldata[j - 1][key]
作為條件
另外,您需要在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.