operation in arrays
I have a question, as I perform mathematic开发者_StackOverflow社区al 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
Try a list comprehension:
>>> list_of_lists = [[1,2],[3,4]]
>>> [sum(li) for li in list_of_lists]
[3, 7]
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]
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
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!
精彩评论