list comprehention

Patrick Maupin pmaupin at gmail.com
Tue Jan 24 00:10:13 CET 2006


Duncan Booth showed how to solve a problem posed by Mathijs.  This is
very similar to Duncan's solution, except I (ab)use setdefault on a
regular basis...

>>> def occurrences(t):
...     res = {}
...     for item in t:
...         res.setdefault(item,[0])[0] += 1
...     return res
...
>>> ref = [2,2,4,1,1]
>>> lst = [2,2,5,2,4]
>>> oref = occurrences(ref)
>>> sum(min(v[0],oref.get(k,[0])[0]) for (k,v) in occurrences(lst).iteritems())
3
>>>

Actually, this brings up an interesting point:

>>> {}.setdefault('foo',0) += 1
SyntaxError: can't assign to function call

I understand why this doesn't work, but it would sure be nice if it
did.  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.

Regards,
Pat




More information about the Python-list mailing list