Pythonic way to sum n-th list element?
Tyler Eaves
tyler at cg1.org
Fri Apr 18 20:38:06 EDT 2003
<posted & mailed>
Alex Martelli wrote:
> Tim Gahnström /Bladerman wrote:
>
>>
>> "Evan Simpson" <evan at 4-am.com> wrote in
>>> Guy Middleton wrote:
>>> > >>> reduce(lambda a, b: a+b, [y[1] for y in x])
>>> >
>>> > But I don't really like lambda, is there a better way to do this?
>>>
>>> What's wrong with:
>>>
>>> t = 0
>>> for y in x:
>>> t += y[1]
>>>
>>> The extra variable? The number of lines?
>>
>> I am really curious about that to, I would most definitley say that this
>> is the most pythonic way. It is simple and easily readabel by anyone and
>> I am sure it is just as fast any of the other way.
>
> Quite. Performance is easy to measure, rather than guess at:
>
> [alex at lancelot python2.3]$ python -O timeit.py -s"lst=[('a',1), ('b',2),
> ('c',3)]*100" -s'import operator' 'x=reduce(lambda x,y: x+y[1], lst, 0)'
> 1000 loops, best of 3: 235 usec per loop
>
> [alex at lancelot python2.3]$ python -O timeit.py -s"lst=[('a',1), ('b',2),
> ('c',3)]*100" -s'import operator' 'x=reduce(operator.add,[y[1] for y in
> lst])'
> 1000 loops, best of 3: 277 usec per loop
>
> [alex at lancelot python2.3]$ python -O timeit.py -s"lst=[('a',1), ('b',2),
> ('c',3)]*100" -s'import operator' 'x=0' 'for y in lst: x+=y[1]'
> 10000 loops, best of 3: 103 usec per loop
>
> Using lists 10 or 100 times as long seems to show O(N) behavior for
> each case, as could be expected. So, the simplest (and I would agree
> thereby most Pythonic) approach is over twice as fast as the fancy ones
> (measurements on 2.2.2 seem to show similar results, all approaches
> being about 20% slower than in 2.3, uniformly).
>
>
> Alex
Wow, I feel vindicated now for never trying to wrap my brain around stuff
like list comprehensions. *g*
More information about the Python-list
mailing list