如何在python中为for循环追加列表

2024-07-02 14:32:18 发布

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

我花了几个小时在这上面,但我无法理解发生了什么。我相信这在其他语言(例如Javascript)中也能工作,但在Python中我不知道发生了什么

我使用的是一个简单的MongoDB数据结构,包括

字段1:“值1” 字段2:“值2” 菲尔登:“瓦伦” fieldM:数组

目标是打印出数组的每个值及其“父项”。我为此编写的Python函数如下所示

def manageonts(sProj):
    ontologies = []
    my_ontology = OntologyDefinition()
    for o in OntologyDefinition.GetAll(sProj): #parent items 
        for l in o.OntologyDefinitions: #child items
            my_ontology.a_type = l[0] #we can access the fields of the array via this method
            my_ontology.a_text = l[1]
            my_ontology.a_subtopic = l[2]
            my_ontology.a_weight = l[3]
            my_ontology.a_weight_if_referenced = l[4]
            ontologies.append(my_ontology)
    for ont in ontologies:
        print(ont.a_text)

而OntologyDefinition是一个类,每个“列”都有字段,包括数组的字段

我假设最后一个循环将返回如下结果

database
date
data
datum
design
event
figure

但是ontologies列表似乎只包含最后一个值:

capacity
capacity
capacity
capacity
capacity
capacity

我做错了什么?我特别感兴趣的是为什么会发生这种行为。谢谢大家的帮助


Tags: thetextinformyitems数组ontology