list comprehension
Duncan Booth
duncan.booth at invalid.invalid
Tue Jan 24 04:04:23 EST 2006
Patrick Maupin wrote:
>>>> def occurrences(t):
> ... res = {}
> ... for item in t:
> ... res.setdefault(item,[0])[0] += 1
> ... return res
>
...
> I think somebody was mentioning "mutable ints" at one point,
> which is basically what I abuse [0] to provide. If I were doing a lot
> of this in one place, I would code a mutable integer class, and then
> the rest of the code would get simpler.
Or you could use the facilities built in to Python: use the get method as
Bryan did, and the code gets simpler without using mutable integers.
I prefer writing an 'if' statement here, Bryan prefers 'get', that's just a
choice of style. But 'setdefault' here, that has no style.
More information about the Python-list
mailing list