2

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'

0

1 Answer 1

9

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) 
Sign up to request clarification or add additional context in comments.

3 Comments

Hmm, I received error, please look at EDIT 2; There is not always 3 elements it's random data, so random "inputs"...
First example didnt' use casting. I updated it to change the values into floats.
Maybe you know how can i get length of this array. I know that it's something in this way len(x); but this is for array. It must count all elements except the last one of x "matrix". So in my case result must be 6. thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.