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
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 =).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With