Python - How to get the first row of each list?
12,153
Solution 1
Use zip()
:
>>> data = [[204.0, u'stock'], [204.0, u'stock']]
>>> zip(*data)
[(204.0, 204.0), (u'stock', u'stock')]
>>> column1, column2 = zip(*data)
>>> column1
(204.0, 204.0)
>>> column2
(u'stock', u'stock')
Or, izip()
from itertools
:
>>> from itertools import izip
>>> column1, column2 = izip(*data)
>>> column1
(204.0, 204.0)
>>> column2
(u'stock', u'stock')
Solution 2
A simple list comprehension will do the trick.
data = [[204.0, u'stock'], [204.0, u'stock']]
column1 = [i[0] for i in data]
column2 = [i[1] for i in data]
>>> column1
[204.0, 204.0]
>>> column2
['stock', 'stock']
Author by
André
Updated on June 28, 2022Comments
-
André almost 2 years
I need to get each row of a list and make a new list. Let me explain.
I have this:
data = [[204.0, u'stock'], [204.0, u'stock']]
I need to transform in this:
column1 = [204.0, 204.0] colunm2 = [u'stock', u'stock']
Any clues on how can this be done?
Best Regards,