我在Python中有两个类变量,例如澳大利亚人和美国人具有相同的属性,但又是分开的,因此我可以区分两者。我将它们组合成一个数组,以根据年龄对它们进行排序。现在,我希望按如下所示显示它们,但是我正在努力寻找一种方法来做到这一点。我是Python脚本编写的新手,仍然在学习。
class Aus(object):
def __init__(self, Name, Age, Height):
self.Name = Name
self.Age = Age
self.Height = Height
class US(object):
def __init__(self, Name, Age, Height):
self.Name = Name
self.Age = Age
self.Height = Height
John = Aus("John", 22, 153)
Steve = Aus("Steve", 15, 180)
Henry = PC("Henry", 20, 192)
Tim = PC("Tim", 85, 160)
Aussies = [John, Steve, Henry, Tim]
Mary = US("Mary", 21, 178)
Sue = US("Sue", 80, 159)
Americans = [Mary, Sue]
Total = Aussies + Americans
Total.sort(key=lambda x: x.Age, reverse=True)
我希望输出结果是这样的
Tim -> 85 Years/160 cm
Sue -> 80 Years/159 cm
John -> 22 Years/153 cm
Mary -> 21 Years/178 cm
等
有没有办法做到这一点?
答案 0 :(得分:2)
一种方法是定义自己的__str__
:
请注意,我假设 Henry 和 Tim 也是Aus
:
class Intro(object):
def __str__(self):
return "%s -> %s Years/%s cm" % (self.Name, self.Age, self.Height)
class Aus(Intro):
def __init__(self, Name, Age, Height):
self.Name = Name
self.Age = Age
self.Height = Height
class US(Intro):
def __init__(self, Name, Age, Height):
self.Name = Name
self.Age = Age
self.Height = Height
John = Aus("John", 22, 153)
Steve = Aus("Steve", 15, 180)
Henry = Aus("Henry", 20, 192)
Tim = Aus("Tim", 85, 160)
Aussies = [John, Steve, Henry, Tim]
Mary = US("Mary", 21, 178)
Sue = US("Sue", 80, 159)
Americans = [Mary, Sue]
Total = Aussies + Americans
然后将sorted
与str
一起使用:
[str(s) for s in sorted(Total, key=lambda x:x.Age, reverse=True)]
输出:
['Tim -> 85 Years/160 cm',
'Sue -> 80 Years/159 cm',
'John -> 22 Years/153 cm',
'Mary -> 21 Years/178 cm',
'Henry -> 20 Years/192 cm',
'Steve -> 15 Years/180 cm']
答案 1 :(得分:0)
您几乎完成了所有工作。我对您的代码进行了一些小的更改,我认为这是最佳做法。
class Person(object):
def __init__(self, Name,Age,Height,Country):
self.Name = Name
self.Age = Age
self.Height = Height
self.Country = Country
John = Person("John", 22, 153,"Australia")
Steve = Person("Steve", 15, 180,"Australia")
Henry = Person("Henry", 20, 192,"Australia")
Tim = Person("Tim", 85, 160,"Australia")
Aussies = [John, Steve, Henry, Tim]
Mary = Person("Mary", 21, 178,"US")
Sue = Person("Sue", 80, 159,"US")
Americans = [Mary, Sue]
Total = Aussies + Americans
Total.sort(key=lambda x: x.Age, reverse=True)
for i in Total:
print(i.Name + " -> " + str(i.Age) + " Years/" + str(i.Height) + "cm")
输出
Tim -> 85 Years/160cm
Sue -> 80 Years/159cm
John -> 22 Years/153cm
Mary -> 21 Years/178cm
Henry -> 20 Years/192cm
Steve -> 15 Years/180cm