【问题标题】:How to append list in for loop in python [duplicate]如何在python中的for循环中附加列表[重复]
【发布时间】:2020-11-22 15:34:36
【问题描述】:

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

我正在使用一个简单的 MongoDB DataStructure,它包含

字段1:“值1” 字段 2:“值 2” 字段:“值” 字段M:数组

目标是打印出数组的每个值及其“父级”。我为此目的编写的 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 列表似乎只包含 last 值:

capacity
capacity
capacity
capacity
capacity
capacity

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

【问题讨论】:

    标签: python


    【解决方案1】:

    你需要移动这条线:

    my_ontology = OntologyDefinition()
    

    for 循环内。否则你只会创建一个 OntologyDefinition 并多次引用它,每次循环都会覆盖它的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-26
      • 1970-01-01
      • 1970-01-01
      • 2020-08-11
      • 2019-04-05
      • 2017-07-10
      • 1970-01-01
      • 2019-07-26
      相关资源
      最近更新 更多