Summing/combining tuples

Larry Hudson orgnut at yahoo.com
Wed May 18 22:58:32 EDT 2016


On 05/18/2016 05:59 PM, DFS wrote:
> Have  aList = [
> ('x','Name1', 1, 85),
> ('x','Name2', 3, 219),
> ('x','Name2', 1, 21),
> ('x','Name3', 6, 169)
> ]
>
> want
>
> aList = [
> ('Name1', 1, 85),
> ('Name2', 4, 240),
> ('Name3', 6, 169)
> ]
>
>
> This drops the first element in each tuple:
> alist = [(b,c,d) for a,b,c,d in alist]

Slicing may be more efficient (perhaps, perhaps not -- don't know).  And probably effectively no 
difference, but slightly shorter to write.

alist = [t[1:] for t in alist]

>
> And this summation creates 2 lists that then have to be combined:
>
> groups1 = defaultdict(int)
> for nm, matches, words in alist:
>      groups1[nm] += matches
>
> groups2 = defaultdict(int)
> for nm, matches, words in alist:
>      groups2[nm] += words
>
>
>
> Is there something shorter and sweeter for the summation?
>
> Thanks
>

Why two loops?  Put both summations in a single loop.  Then you're only scanning the alist once 
instead of twice.

groups1 = defaultdict(int)
groups2 = defaultdict(int)
for nm, matches, words in alist:
     groups1[nm] += matches
     groups2[nm] += words

      -=- Larry -=-




More information about the Python-list mailing list