我有一个小程序,应该是细胞从出生到减数分裂到死亡的生命周期的基本模型。尽管我已经弄明白了其中的大部分,但我还是坚持以下几点:
class cell:
def __init__(self):
self.name = random.randint(1,1000)
self.type = [random.choice(b)]
self.age = 0
self.evos = random.randint(1,5) #<-- need to access this attr
def displayEvolutions(pop): # one of many methods, this one is a problem
p = []
for i in pop:
p.append(i.evos)
return p
community = [#a bunch of class instances]
cells_that_evolved = displayEvolutions(community)
它应该遍历类实例的列表community
,访问它们的evo
属性,用该数据填充cells_that_evolved
,然后向用户显示该列表。你知道吗
应该是这样的:
cells_that_evolved = displayEvolutions(community)
print(cells_that_evolved)
[3, 4, 5, 6, 7, 8, 3, 1, 5] #<--- 9 instances, 9 values = instance.evos
但是,无论我尝试什么,它都只将第一个值附加到列表中,因此该列表如下所示:
[3]
为什么?你知道吗
您有缩进问题:
第一次通过循环时,当遇到
return p
时,返回当前值p
,函数终止。相反,应该在循环完成后返回p
,方法是取消该行的标识:编写函数更优雅的方法是使用list comprehension:
相关问题 更多 >
编程相关推荐