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,
最好的祝福,
3 个解决方案
#1
5
Use zip()
:
使用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
:
或者,来自itertools的izip():
>>> from itertools import izip
>>> column1, column2 = izip(*data)
>>> column1
(204.0, 204.0)
>>> column2
(u'stock', u'stock')
#2
3
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']
#3
0
may be , in one line
可能是,在一行
>>> data = [[204.0, u'stock'], [204.0, u'stock']]
>>> columns = [ [d[k] for d in data] for k in range(2)]
[[204.0, 204.0], ['stock', 'stock']]
>>> columns[0]
[204.0, 204.0]
and if the size of variable can change you can do this :
如果变量的大小可以改变,你可以这样做:
columns = [ [d[k] for d in data] for k in range(max(map(len,data)))]
#1
5
Use zip()
:
使用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
:
或者,来自itertools的izip():
>>> from itertools import izip
>>> column1, column2 = izip(*data)
>>> column1
(204.0, 204.0)
>>> column2
(u'stock', u'stock')
#2
3
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']
#3
0
may be , in one line
可能是,在一行
>>> data = [[204.0, u'stock'], [204.0, u'stock']]
>>> columns = [ [d[k] for d in data] for k in range(2)]
[[204.0, 204.0], ['stock', 'stock']]
>>> columns[0]
[204.0, 204.0]
and if the size of variable can change you can do this :
如果变量的大小可以改变,你可以这样做:
columns = [ [d[k] for d in data] for k in range(max(map(len,data)))]