我需要获取列表的每一行并创建一个新列表。让我解释一下。
我有这个:
data = [[204.0, u'stock'], [204.0, u'stock']]
我需要转变:
column1 = [204.0, 204.0]
colunm2 = [u'stock', u'stock']
有关如何做到这一点的任何线索?
最诚挚的问候,
答案 0 :(得分:5)
使用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')
或者来自itertools
的{{3}}:
>>> from itertools import izip
>>> column1, column2 = izip(*data)
>>> column1
(204.0, 204.0)
>>> column2
(u'stock', u'stock')
答案 1 :(得分:3)
一个简单的列表理解就可以解决问题。
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']
答案 2 :(得分:0)
可能在一行
>>> 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)))]