我需要获取列表的每一行并制作一个新列表。让我解释。
我有这个:
data = [[204.0, u'stock'], [204.0, u'stock']]
我需要对此进行改造:
column1 = [204.0, 204.0]
colunm2 = [u'stock', u'stock']
关于如何做到这一点的任何线索?
最好的祝福,
使用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')
或者,izip()
从itertools
:
>>> from itertools import izip
>>> column1, column2 = izip(*data)
>>> column1
(204.0, 204.0)
>>> column2
(u'stock', u'stock')
一个简单的列表推导就可以解决问题。
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']
可能在一行中
>>> 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]
如果变量的大小可以改变,你可以这样做:
columns = [ [d[k] for d in data] for k in range(max(map(len,data)))]