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

Time:03-05

I have a code chunk

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']
        
    ]

I created a relgraph list. Append the entries of list. With each iteration, I want to recreate this list. Also, dump these lists into json file. How do I do that.

I tried to put relgraph=[] before and after for statement but it gives me an error saying invalid syntax

CodePudding user response:

What you've written isn't a for loop, it's a list comprehension that has been sort of hacked up to behave like a for loop by putting a bunch of statements into tuples. Don't do that; if you want to write a for loop, just write a for loop. I think what you're trying to write is:

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)

If you were to write this as a list comprehension, you'd do it by building the individual relgraph lists in place via another comprehension, not by binding a name to it and doing a bunch of append statements. Something like:

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