我有一個代碼塊
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檔案中。我怎么做。
我試圖在宣告relgraph=[]之前和之后放置,for但它給了我一個錯誤說invalid syntax
uj5u.com熱心網友回復:
你寫的不是一個回圈,它是一個串列推導式,通過將一堆陳述句放入元組中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(),
)]
]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/438425.html
