[英]Sort dictionary with Objects as keys
我是python的新手,我正在嘗試對有一些對象作為鍵的字典進行排序。
我有一個類Student(studID, name)
,它是字典的鍵,並且是一個分數數組,它是字典的值。
看起來是這樣的:
dictEx = {
Student: [5,6],
Student: [7,8],
Student: [10,9]
}
該對象Student具有方法getName()來獲取學生姓名。 我要完成的工作是,僅當學生具有相同的姓名時,才按學生姓名對該詞典進行排序,然后按年級進行排序。 (例如,如果我有兩個叫安德魯的學生)
您必須在字典中創建每個類的實例:
class Student:
def __init__(self, *args):
self.__dict__ = dict(zip(['name', 'grade'], args))
def getName(self):
return self.name
def __repr__(self):
return "{}({})".format(self.__class__.__name__, ' '.join('{}:{}'.format(a, b) for a, b in self.__dict__.items()))
dictEx = {
Student('Tom', 10): [5,6],
Student('James', 12): [7,8],
Student('James', 7): [10,9],
}
new_dict = sorted(dictEx.items(), key=lambda x:(x[0].getName(), x[-1]))
輸出:
[(Student(grade:12 name:James), [7, 8]), (Student(grade:7 name:James), [10, 9]), (Student(grade:10 name:Tom), [5, 6])]
但是請注意,字典是無序的,因此您將不得不依賴存儲在new_dict
中的元組列表或使用collections.OrderedDict
:
from collections import OrderedDict
d = OrderedDict()
new_dict = sorted(dictEx.items(), key=lambda x:(x[0].getName(), x[-1]))
for a, b in new_dict:
d[a] = b
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.