Matrix problem Python

2019-07-18 17:33发布

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'

标签: python sum
1条回答
我只想做你的唯一
2楼-- · 2019-07-18 18:03

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) 
查看更多
登录 后发表回答