9
I’m working on Python 2.7. I have this result:
Resultado=[['A','B','C'],['D','E','F'],['G','H','I']]
How can I turn this into a list? And get the following:
Lista=['A','B','C','D','E','F','G','H','I']
Thank you!
9
I’m working on Python 2.7. I have this result:
Resultado=[['A','B','C'],['D','E','F'],['G','H','I']]
How can I turn this into a list? And get the following:
Lista=['A','B','C','D','E','F','G','H','I']
Thank you!
7
To make a single list of:
Resultado=[['A','B','C'],['D','E','F'],['G','H','I']]
Do (no need to import external libs for this, this is what I recommend):
Lista = [item for sublista in Resultado for item in sublista]
Alternatives:
Lista = []
for i in Resultado:
Lista.extend(i)
print Lista #['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
Or:
Lista = []
[Lista.extend(i) for i in Resultado]
print Lista #['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
4
I would do it using the method chain
of itertools
from itertools import chain
Resultado = [['A','B','C'],['D','E','F'],['G','H','I']]
Lista = list(chain(*Resultado))
print (Lista); # ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
Just for more information on how to search if necessary, the name of this operation in English is called flatten
. It means you’re turning a multilevel list into a one-dimensional list.
Browser other questions tagged python python-2.7
You are not signed in. Login or sign up in order to post.