Skip to content Skip to sidebar Skip to footer

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.

Solution 1:

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) 

Post a Comment for "Matrix Problem Python"