为什么我的功能会尽早放弃?

时间:2016-11-21 05:32:50

标签: python list class python-3.x for-loop

我有一个小程序,应该是细胞从出生到减数分裂到死亡的生命周期的基本模型。虽然我已经弄明白其中的大部分内容,但我仍然坚持以下内容:

.project

它应该遍历类实例列表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

为什么?

1 个答案:

答案 0 :(得分:2)

您有缩进问题:

def displayEvolutions(pop):
    p = []
    for i in pop:
        p.append(i.evos)
        return p

第一次通过循环,遇到return p时,返回p的当前值,函数终止。相反,您应该在循环完成后返回p,方法是取消紧接该行:

def displayEvolutions(pop):
    p = []
    for i in pop:
        p.append(i.evos)
    return p

编写函数的更优雅的方法是使用list comprehension

def displayEvolutions(pop):
    return [i.evos for i in pop]