Search for mapping solution
Martin Maney
maney at pobox.com
Thu Jul 10 13:01:35 EDT 2003
I dedicate this monument to Alan Kennedy, without whom I would probably
never have tried to compress things so. :-)
Sean Ross <sross at connectmail.carleton.ca> wrote:
> lines = [['fred','333','0.10'],['sam','444','1'],['fred','333','0.50']]
> costs = {}
> # nearly identical to Achim's solution, but with a list comp.
> [costs.__setitem__(name, costs.get(name,0)+float(price))
> for name, number, price in lines]
> print costs
> # outputs: {'sam': 1.0, 'fred': 0.60}
It isn't really one line though, is it? For truly cryptic terseness
you want to swing functional (I shall adopt your interpretation of the
third element although seeing it as a list of integers would have
allowed for additional functional yumminess):
>>> lines = [['fred','333','0.10'],['sam','444','1'],['fred','333','0.50']]
>>> reduce(lambda d,x: d.update({x[0]: d.get(x[0],0.0) + float(x[2])}) or d, [{}] + lines)
{'fred': 0.59999999999999998, 'sam': 1.0}
Mind you, I normally despise the whole one-liner phenomenon, which
makes me almost pleased about the inelegant necessity of that 'or d' -
blame it on either update's lack of a return value or lambda's
emasculation. But as I've been working my way through SICP as this
summer's project, it certainly seems odd. :-/
--
automation: replacing what works with something that almost works,
but which is faster and cheaper. - attributed to Roger Needham
More information about the Python-list
mailing list