0

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

1
  • You're confusing a for loop with a list comprehension. Commented Feb 28, 2022 at 15:55

1 Answer 1

1

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(),
    )]
]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.