我的排序功能有问题。我创建了一个包含对象Ship的字典。我试着用船的名字来整理我的字典。排序功能正常,但我无法更新字典。除了make print(已排序)之外我说好了整理好的字典,但是当我制作一个打印(Dict)时,它已经没有了解......唯一的办法是在我的函数排序中添加一个返回...谢谢你的帮助
详细信息:
类Ship(对象):
def __init__(self, id, name=None, country=None):
self.id, self.name, self.country = id, name, country
self.position = []
def __repr__(self):
return repr((self.id, self.name, self.country, self.position))
def add_position(self, position):
latitude, longitude, datestamp = position[0], position[1], position[2]
self.position.append(Position(latitude, longitude, datestamp))
self.sort_position()
def sort_position(self):
self.position = sorted(self.position, key=lambda x: x.datestamp)
类ShipDict(dict):
def __init__(self):
self.__dict__ = {}
pass
def sort_dict(self):
print("Resultat de la fonction de tri : ",sorted(self.items(), key=lambda x: x[1].name))
self = sorted(self.items(), key=lambda x: x[1].name)
执行:
bateau1 = Ship(1,'Marchant', 'France')
bateau3 = Ship(3,'Zoo', 'Grece')
bateau2 = Ship(2,'Atlantique', 'Hollande')
Dict = ShipDict()
Dict[1] = bateau1
Dict[2] = bateau2
Dict[3] = bateau3
print("Dictionnaire avant tri: ",Dict)
Dict.sort_dict()
print("Dictionnaire après tri: ",Dict)
结果:
Dictionnaire avant tri: {1: (1, 'Marchant', 'France', []), 2: (2, 'Atlantique', 'Hollande', []), 3: (3, 'Zoo', 'Grece', [])}
Resultat de la fonction de tri : [(2, (2, 'Atlantique', 'Hollande', [])), (1, (1, 'Marchant', 'France', [])), (3, (3, 'Zoo', 'Grece', []))]
Dictionnaire après tri: {1: (1, 'Marchant', 'France', []), 2: (2, 'Atlantique', 'Hollande', []), 3: (3, 'Zoo', 'Grece', [])}