Reputation: 2000
I have a matrix of values, like:
matrix = [
[1,2,3],
[5,6,7]
]
I want to normalize them, so that each row sums to one. This is pretty simple with an approach like:
result = []
for x in matrix:
curr_row = [z/sum(x) for z in x]
result.append(curr_row)
I'm wondering if there's a way to do this with a list comprehension.
The closest I've gotten is
result = [x/sum(y) for y in matrix for x in y]
but this collapses it all into one list.
Upvotes: 1
Views: 113
Reputation: 18027
You are almost there.
from __future__ import division # for Python2
results = [[item/sum(row) for item in row] for row in matrix] # a list of lists
print(results)
# Output
[[0.16666666666666666, 0.3333333333333333, 0.5], [0.2777777777777778, 0.3333333333333333, 0.3888888888888889]]
Upvotes: 2