list comprehension return a list and sum over in loop

Oscar Benjamin oscar.j.benjamin at gmail.com
Fri Dec 12 11:47:43 EST 2014


On 12 December 2014 at 06:22, KK Sasa <genwei007 at gmail.com> wrote:
> Hi there,
>
> The list comprehension is results = [d2(t[k]) for k in xrange(1000)], where d2 is a function returning a list, say [x1,x2,x3,x4] for one example. So "results" is a list consisting of 1000 lists, each of length four. Here, what I want to get is the sum of 1000 lists, and then the result is a list of length four. Is there any efficient way to do this? Because I found it is slow in my case. I tried sum(d2(t[k]) for k in xrange(1000)), but it returned error: TypeError: unsupported operand type(s) for +: 'int' and 'list'. Thanks.

Use numpy.sum:

>>> import numpy as np
>>> a = [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]]
>>> np.sum(a, 0)
array([6, 6, 6, 6])
>>> np.sum(a, 1)
array([ 4,  8, 12])

The second argument to numpy.sum is the dimension along which you want
to sum e.g. rows or columns.


Oscar



More information about the Python-list mailing list