开发者

Matrix problem Python

For example if I have matrix:

开发者_开发问答x=[['1', '7', 'U1'], ['1.5', '8', 'U1'], ['2', '5.5', 'U2']]

How can I take all data from x, except the last one. Then I need to sum this elements.


This is what I need: sum=1+7+1.5+8+2+5.5= ??

Thanks



EDIT2:


I try:

> x=[['1', '7', 'U1'], ['1.5', '8',
> 'U1'], ['2', '5.5', 'U2']]
> 
> sum(sum(el[:-1]) for el in x)

But received error:

Traceback (most recent call last):

File "xxx.py", line 3, in sum(sum(el[:-1]) for el in x) File "xxx.py", line 3, in sum(sum(el[:-1]) for el in x) TypeError: unsupported operand type(s) for +: 'int' and 'str'


You can take all elements apart from the last one indexing with [:-1].

To take that sum, try sum(sum(float(el) for el in els[:-1]) for els in x).

If you actually have strings in the list, you might need to cast the elements. Also, if there are always 3 elements, this could be a bit faster:

sum(float(a) + float(b) for a,b,_ in x) 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜