[英]I get the correct output only when I add another return value in Python3.x
[英]Total ordering does not return for expected output python3.x
我有一個包含 6 個人的輸入,每個人都有姓名和號碼。 我正在嘗試編寫排序函數來根據它們的數量對它們進行排序。 如果兩個數字相同,我會嘗試根據名稱對它們進行排序。
為了實現它,我使用了 total_ordering。 但是它不會返回預期的輸出。
import numpy as np
from functools import total_ordering
@total_ordering
class Person(object):
def __init__(self, name, number):
self.name=name
self.number=number
def __repr__(self):
return "{}, {}".format(self.number, self.name)
def __lt__(self, other):
return self.number<other.number
def __eq__(self, other):
return (self.number==other.number and self.name==other.name) or self.number==other.number
def __le__(self, other):
return (self.number==other.number and self.name<other.name) or self.number<other.number
customList=[
Person('object', 99),
Person('michael', 1),
Person('theodore', 21),
Person('amazon', 21),
Person('life', 42),
Person('tree', 42)
]
a=sorted(customList)
print(a)
代碼片段返回[1, michael, 21, theodore, 21, amazon, 42, life, 42, tree, 99, object]
但是我期望[1, michael, 21, amazon, 21, theodore, 42, life, 42, tree, 99, object]
謝謝你。
我會寫
def __lt__(self, other):
return (self.number, self.name) < (other.number, other.name)
__eq__
和__le__
類似
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.