gpt4 book ai didi

python - 根据字典对列表进行排序(初学者)

转载 作者:行者123 更新时间:2023-12-04 02:38:05 25 4
gpt4 key购买 nike

我有以下列表:

listofanimals = ['Dog', 'Cat', 'Frog', 'Tiger', 'Sheep', 'Lion']

我想根据字典对这个列表进行排序:

score_card = {0: 'Sheep', 1: 'Dog', 2: 'Cat', 3: 'Tiger', 4: 'Frog', 5: 'Lion'}

最终列表的顺序必须是从 0 到 5,即

numberorder = [0, 1, 2, 3, 4, 5]

我想在一个函数中创建它。这就是我所拥有的:

def sorter():
listofanimals = ['Dog', 'Cat', 'Frog', 'Tiger', 'Sheep', 'Lion']
score_card = {0: 'Sheep', 1: 'Dog', 2: 'Cat', 3: 'Tiger', 4: 'Frog', 5: 'Lion'}
numbers = [0, 1, 2, 3, 4, 5]
finallist = []
for i in listofanimals:
print(numbers[listofanimals.index(i)])
q.append(numbers[listofanimals.index(i)])
print(q)
q = sorted(q)
finallist = [score_card[j] for j in q]
return finallist

我不知道如何将 listofanimals 转换为数字,所以我可以对数字进行排序,然后反馈到字典中以获取值,但我就是无法让它工作。任何帮助表示赞赏。

最佳答案

翻转你的字典

data = {'Sheep':0, 'Dog':1,  'Cat':2, 'Tiger': 3, 'Frog':4, 'Lion':5} 

(如果需要,您可以通过编程方式反转它,请参阅其他答案)

现在你可以简单地

my_sorted_list = sorted(my_list,key = data.get)

关于python - 根据字典对列表进行排序(初学者),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60717952/

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