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, 开发者_Python百科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
>>> 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.
精彩评论