list comprehension return a list and sum over in loop

pecore at pascolo.net pecore at pascolo.net
Sat Dec 13 07:38:53 EST 2014


KK Sasa <genwei007 at gmail.com> writes:

> 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.

Why didn't you  follow Mark Lawrence's advice? 

In your problem, results is a list of N sublists, each containing
exactly four numerical values,

Let's try with N=2

In [36]: results = [d2(t[k]) for k in range(2)]
In [37]: print results
[[1, 2, 3, 4], [5, 6, 7, 8]]

Let's try the obvious method to sum

In [38]: [sum(el) for el in results]
Out[38]: [10, 26]

not what you're looking for, but what if we had 

In [39]: [sum(el) for el in zip(*results)]
Out[39]: [6, 8, 10, 12]

correct.

BTW, as you're using the scientific stack the answer of Christian
Gollwitzer is the more appropriate.



More information about the Python-list mailing list