Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

From matrix to list of words

I have a NumPy r by c matrix of zeroes and ones. And I have a list of c words. I want to return a list of length r where each element is a space delimited string made up of only those words that match 1's in that matrix's row. Here's an example:

matrix=np.array([[0,0,1],[1,0,1],[0,1,1]])
words=['python','c++','.net']

output=[]
for row in range(matrix.shape[0]):
    output.append( ' '.join([words[i]  for i in range(matrix.shape[1]) if matrix[row,i]==1]))

What is a Pythonic way to accomplish this?

Thanks,

G

like image 811
ADJ Avatar asked Oct 21 '22 20:10

ADJ


1 Answers

Behold:

>>> [' '.join(word for include_word, word in zip(row, words) if include_word) 
     for row in matrix]
['.net', 'python .net', 'c++ .net']

This was a fun one =).

like image 152
Claudiu Avatar answered Oct 23 '22 09:10

Claudiu