thaking
thaking

Reputation: 3635

Python sum trouble

I have next problem:

x=[['1', '7', 'U1'], ['1.5', '8', 'U1']]
y=sum(sum(float(el) for el in els[:-1]) for els in x) 

print(x)
print(y)

In this code sum, sum all numbers, but I want to sum from first ['1', '7', 'U1'], first number, and from second ['1.5', '8', 'U1'] first number, and same for second...

so final result fill look as "matrix" :

y=
[ [2.5],                                #1+1.5=2.5
  [15]]                                 #7+8=15

Upvotes: 2

Views: 189

Answers (1)

interjay
interjay

Reputation: 110203

>>> x=[['1', '7', 'U1'], ['1.5', '8', 'U1']]
>>> zip(*x)
[('1', '1.5'), ('7', '8'), ('U1', 'U1')]
>>> [[sum(float(n) for n in nums)] for nums in zip(*x)[:-1]]
[[2.5], [15.0]]

zip(*x) is a simple way to transpose the matrix (switch rows <--> columns), and this allows you to easily sum each row.

Upvotes: 8

Related Questions