gpt4 book ai didi

python - 如何在Python中的字典列表上进行插入排序?

转载 作者:太空宇宙 更新时间:2023-11-03 19:01:59 25 4
gpt4 key购买 nike

我有一个包含各种键的字典列表,所有键都是整数,我需要编写一个函数,使用插入排序按特定键对它们进行排序。

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]作为条件

您还需要更改j在你的 while 循环中或者它可以永远运行

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

关于python - 如何在Python中的字典列表上进行插入排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15801027/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com