【问题标题】:How can I get attributes of induvidual items in a list of Objects in Python?如何在 Python 中的对象列表中获取单个项目的属性?
【发布时间】:2022-01-25 09:22:30
【问题描述】:

我有一个名为 Civilizations 并初始化为的对象列表

Civilizations = []

我还有一个文明类和母舰类

class Civilization():
    name = "Default Civilization"
    hero_count = 1
    builder_count = 20
    mothership = []
    def __init__(self, param, name, hero_count):
        self.param = param
        self.name = name
        self.hero_count = hero_count

class Mothership():
    name = ""
    coord_x = 0.0
    coord_y = 0.0
    coord_size = 50
    def __init__(self, name, coord_x, coord_y):
        self.name = name
        self.coord_x = coord_x
        self.coord_y = coord_y

red = Civilization(10, "RED", 1)
blue = Civilization(12, "BLUE", 1)
Civilizations.append(red)
Civilizations.append(blue)

orange = Mothership("Stasis", 300.0, 500.0)
red.mothership.append(orange)
yellow = Mothership("Prime", 350.0, 550.0)
blue.mothership.append(yellow)    

x = []
y = []
s = []
n = []

print(Civilizations)
for t in Civilizations:
    a = t.mothership[0]
    print(a)
    # x.append(a.coord_x)
    # y.append(a.coord_y)
    # s.append(a.coord_size)
    # n.append(a.name)
    print(n)

print(x)

打印 (a) 结果给我们两次 <__main__.Mothership object at 0x0000029412E240A0>,而 x 最终看起来像 [300,300]。有没有办法遍历对象并获取它们的各个属性?我试图让 x 看起来像 [300, 350]

感谢您的帮助!

【问题讨论】:

  • mothershipCivilization类属性,由类的每个实例共享。您需要一个实例属性,因此请改为在__init__() 中创建该列表。

标签: python list class


【解决方案1】:

问题在于以下两行代码。

for t in Civilizations:
    a = t.mothership[0]

文明类中的母舰列表将附加两个对象。 Civilizations.mothership = [ obj_orange, obj_yellow ]

因为您的母舰列表有两个索引值 0 和 1。 在您的代码中,您仅使用索引 0 来检索整个循环中的值。 您的循环运行两次并返回相同的对象 (obj_orange) 两次。

您必须从索引 0 和 1 中检索两个值,如下所示

for t in Civilizations:
    a = t.mothership[0]
    b = t.mothership[1]

或者您可以简单地使用“枚举”,这在您不知道列表中元素数量的情况下是非常好的做法。

for i, t in enumerate(Civilizations):
    print(t.mothership[i])

其中 i = 索引号,t = 值

【讨论】:

    猜你喜欢
    • 2010-09-27
    • 2013-10-10
    • 1970-01-01
    • 2019-10-17
    • 1970-01-01
    • 1970-01-01
    • 2012-02-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多