gpt4 book ai didi

python - 如何打印属于单个数组的 2 个类变量?

转载 作者:太空宇宙 更新时间:2023-11-04 01:56:36 25 4
gpt4 key购买 nike

我在 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

有什么办法可以实现吗?

最佳答案

一种方法是定义您自己的 __str__:

请注意,我假设 HenryTim 也是 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

然后将 sortedstr 一起使用:

[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']

关于python - 如何打印属于单个数组的 2 个类变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56679250/

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