如何在 python 中的每次循环迭代中更新列表

How to renew the list with each iteration of loop in python

我有一个代码块

if show_relations:
    _print('Relations:')

    entities = graph['entities']
    relgraph=[]
    relations_data = [
        [
            
            entities[rel['subject']]['head'].lower(),
            relgraph.append(entities[rel['subject']]['head'].lower()),
            
            rel['relation'].lower(),
            relgraph.append(rel['relation'].lower()),
            
            
            entities[rel['object']]['head'].lower(),
            relgraph.append(entities[rel['object']]['head'].lower()),
            _print(relgraph)
            
        ]
        for rel in graph['relations']
        
    ]

我创建了一个 relgraph 列表。附加列表的条目。每次迭代,我都想重新创建这个列表。 此外,将这些列表转储到 json 文件中。我该怎么做。

我试图在 for 语句之前和之后放置 relgraph=[] 但它给我一个错误 invalid syntax

你写的不是 for 循环,它是一个列表推导式,通过将一堆语句放入元组中,它的行为类似于 for 循环.不要那样做;如果你想写一个for循环,就写一个for循环。我想你想写的是:

relations_data = []
for rel in graph['relations']:
    relgraph=[]
    relgraph.append(entities[rel['subject']]['head'].lower()),
    relgraph.append(rel['relation'].lower()),
    relgraph.append(entities[rel['object']]['head'].lower()),
    relations_data.append(relgraph)

如果你要把它写成一个列表理解,你会通过另一个理解构建单独的relgraph列表来做到这一点,而不是通过绑定给它起个名字,然后做一堆 append 语句。类似于:

relations_data = [
    [i for rel in graph['relations'] for i in (
        entities[rel['subject']]['head'].lower(),
        rel['relation'].lower(),
        entities[rel['object']]['head'].lower(),
    )]
]