tags:

views:

92

answers:

4

hello everyone, I have a question, as I perform mathematical operations with an array of lists such as I get the sum of each array list getting a new list with the Valar for the sum of each list in the array.

thanks for any response

+3  A: 

Try a list comprehension:

>>> list_of_lists = [[1,2],[3,4]]
>>> [sum(li) for li in list_of_lists]
[3, 7]
tcarobruce
+1  A: 

If you're going to manipulate lists of numbers to perform some mathematical calculos, you'd better use Numpy's arrays:

>>> import numpy
>>> a = numpy.array([1,2,3])
>>> b = numpy.array([2,6])
>>> a_list = [a,b]
>>> [x.sum() for x in a_list]
[6, 8]

It'll be faster!

Juanjo Conti
hello, thanks for the answers is a good way to add basic elements of an array but does work for arrays of this typea = array ([[1,2,3], [4,5,6], [7,8,9]]) I wish to obtain the sum of each vector of the array something like the sum of the first vector or each vector sum ([1,2,3])
ricardo
+2  A: 

You can also try mapping the lists with the built-in sum function.

>>> a = [11, 13, 17, 19, 23]
>>> b = [29, 31, 37, 41, 43]
>>> c = [47, 53, 59, 61, 67]
>>> d = [71, 73, 79, 83, 89]
>>> map(sum, [a, b, c, d])
<map object at 0x02A0E0D0>
>>> list(_)
[83, 181, 287, 395]
Noctis Skytower
Explanations: 1) In this example map returns a map object instead of a list, like in previous versions of Python. 2) So, the list(something) is needed to convert the map object to a list. 3) In Python's interactive mode, the _ variable contains the most recent output value displayed by the interpreter.
Juanjo Conti
+1  A: 

What I understand is that you have a list of list -- in effect, matrix. You want the sum of each row. I agree with other answerers that you should use numpy.

we can create a mulidimensional array:

>>> import numpy
>>> a = numpy.array([[1,2,3], [4,5,6], [7,8,9]])
>>> a
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

Now we can use a.sum([dimension]) where dimension is how you want to sum the array. Summing each row is dimension 1:

>>> a.sum(1)
array([ 6, 15, 24])

You can also sum each column:

>>> a.sum(0)
array([12, 15, 18])

And sum all:

>>> a.sum()
45
kaizer.se