Given the following list:
[['ORGANIZATION', 'EDUCATION', 'UniversityWon', 'FormMathematics'], ['PERSON', 'Sixth', 'Economics'], ['GPE', 'FrenchUK', 'London']]
I have the following for loop that prints them in the desired way:
for i in output:
print(i[0], '->', ', '.join(i[1:]))
Output of:
ORGANIZATION -> EDUCATION, UniversityWon, FormMathematics
PERSON -> Sixth, Economics
GPE -> FrenchUK, London
How can i save this output into a variable such that if i executed print(variable)
, the above output would be printed?
CodePudding user response:
You just need to assign it to a variable, but make sure you have initialized the variable outside of the for loop first:
variable = ""
for i in output:
variable = i[0] '->' ', '.join(i[1:]) "\n"
print(variable.strip()) # strip() is used to remove the last "\n"
Second approach
It seems the more efficient approach (Thanks to @ThierryLathuille for the comment) would be using list of line and joining them using join
function:
variable = "\n".join([x[0] '->' ', '.join(x[1:]) for x in output])
print(variable)
Output of both above-mentioned answers would be the same:
ORGANIZATION->EDUCATION, UniversityWon, FormMathematics
PERSON->Sixth, Economics
GPE->FrenchUK, London