使用列表推导从元组列表列表中创建矩阵

时间:2017-07-28 07:32:52

标签: python numpy matrix list-comprehension

我有一个元组列表list1

list1 = [[('a',0.01),('b',0.23),('c',1e-7)],
      [('a',0.91),('b',0.067),('c',0.38)]]

我想创建一个numpy矩阵,其中每一行都是list1中元组的第二个值。所以矩阵,我们称之为A,将形成

A = [[0.01,0.23,1e-7],[0.91,0.067,0.38]]
A.shape
>>> (2,3)

到目前为止,我已经设法以缓慢而低效的方式实现这一目标

A = []
for i in range(len(list1)):
    A.append(np.array([v for k,v in list1[i]]))
A = np.array(A)

如何使用列表理解来完成此操作?

1 个答案:

答案 0 :(得分:5)

您需要嵌套列表推导:

np.array([[tup[1] for tup in lst] for lst in list1])
Out: 
array([[  1.00000000e-02,   2.30000000e-01,   1.00000000e-07],
       [  9.10000000e-01,   6.70000000e-02,   3.80000000e-01]])

更好的解决方案是:

np.array(list1)[:,:,1].astype('float')
Out: 
array([[  1.00000000e-02,   2.30000000e-01,   1.00000000e-07],
       [  9.10000000e-01,   6.70000000e-02,   3.80000000e-01]])