为什么我的职能早就放弃了?

2024-10-05 15:24:07 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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]

为什么?你知道吗


Tags: communityself列表thatdefrandomthispop
1条回答
网友
1楼 · 发布于 2024-10-05 15:24:07

您有缩进问题:

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]

相关问题 更多 >