Create a matrix from a list of list of tuples using a list comprehension

I have a list of lists of tuples list1

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

      

and I want to create a numpy matrix where each row will be the second value of the tuple in list1

. Thus, the matrix, let's call it A

, has the form

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

      

So far, I've managed to achieve this in a slow and inefficient way.

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

      

How can I do this using a list comprehension?

+3


source to share


1 answer


To do this, you need nested lists:

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]])

      



The best solution would be:

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]])

      

+5


source







All Articles