python - Create matrix from list of list of tuples using list comprehension -
i have 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 want create numpy matrix each row second value of tuple in list1
. matrix, lets call a
, have form
a = [[0.01,0.23,1e-7],[0.91,0.067,0.38]] a.shape >>> (2,3)
so far have managed achieve in slow , inefficient way
a = [] in range(len(list1)): a.append(np.array([v k,v in list1[i]])) = np.array(a)
how can using list comprehension?
you need nested list comprehensions this:
np.array([[tup[1] tup in lst] lst in list1]) out: array([[ 1.00000000e-02, 2.30000000e-01, 1.00000000e-07], [ 9.10000000e-01, 6.70000000e-02, 3.80000000e-01]])
a better solution 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]])
Comments
Post a Comment