Paul Rubin wrote:
> [EMAIL PROTECTED] writes:
> > I have list of lists of the following form
> >
> > L=[['A', 100], ['B', 300], ['A', 400], ['B', -100]]
> >
> > I want to aggregate these lists, i.e. to reduce L to
> > L=[['A', 500], ['B', 200]] #500 = 100+400, 200=300-100
>
> How about:
>
>     v = {}
>     for name,val in L:
>       v[name] = v.get(name, 0) + val
>     L = v.items()

Followed by L.sort() if the OP really needs his list sorted.
Alternatively, he may prefer to leave it in a dict; in fact, if he had
been using a dict all along and maintaining it on the fly by  "v[name]
= v.get(name, 0) + val", he wouldn't need to batch-fix his data
structure now.

tkpmep, how did you get this list of lists with duplicate keys and
additive values? What do you want to do with it next?

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to