如何存储动态生成的变量?

时间:2018-09-29 16:17:54

标签: python python-3.x

我正在尝试动态生成单元格。每个单元都有一个索引(所以我可以参考它),以及强度,智力和能量的伪随机参数。我的问题是,虽然我可以在单个单元上工作,但找不到在整体上对所有单元执行操作的方法。有没有一种方法,而无需手动将每个单元格键入列表?

class Cell:
    def __init__(self, energy, strength, intelligence):
        self.energy = energy
        self.strength = strength
        self.intelligence = intelligence
cells = {}
k = 1
while k < 100:
    key = "a" + str(k)
    print("Generating cell: " + key)
    cells[key] = Cell(random.randint(1, 100),random.randint(1, 100),random.randint(1, 100))
    k += 1

locals().update(cells)

print(cells)
print(a43.energy)
print(a43.strength)
print(a43.intelligence)   #Make sure the cells exists and work as intended (they do)

输出:

Generating cell: a1
Generating cell: a2
Generating cell: a3
...
Generating cell: a99
{'a1': <__main__.Cell object at 0x031324F0>, 'a2': <__main__.Cell object at 0x0313BD90>, 'a3': <__main__.Cell object at 0x03132430>
...
'a99': <__main__.Cell object at 0x0319A130>}
68
83
66

0 个答案:

没有答案
相关问题