list comprehention

Duncan Booth duncan.booth at invalid.invalid
Fri Jan 20 11:07:31 CET 2006


Mathijs wrote:

> Python beginner here and very much enjoying it. I'm looking for a 
> pythonic way to find how many listmembers are also present in a
> reference list. Don't count duplicates (eg. if you already found a
> matching member in the ref list, you can't use the ref member
> anymore). 
> 
> Example1: 
> ref=[2, 2, 4, 1, 1]
> list=[2, 3, 4, 5, 3]
> solution: 2
> 
> Example2:
> ref=[2, 2, 4, 1, 1]
> list=[2, 2, 5, 2, 4]
> solution: 3 (note that only the first two 2's count, the third 2 in
> the list should not be counted)

Here's the way I would do it:

>>> def occurrences(it):
    res = {}
    for item in it:
        if item in res:
            res[item] += 1
        else:
            res[item] = 1
    return res

>>> ref=[2, 2, 4, 1, 1]
>>> lst=[2, 2, 5, 2, 4]
>>> oref = occurrences(ref)
>>> sum(min(v,oref.get(k,0)) for (k,v) in occurrences(lst).iteritems())
3
>>> lst=[2, 3, 4, 5, 3]
>>> sum(min(v,oref.get(k,0)) for (k,v) in occurrences(lst).iteritems())
2
>>> 

Or in other words, define a function to return a dictionary containing 
a count of the number of occurrences of each element in the list (this 
assumes that the list elements are hashable). Then you just add up the 
values in the test list making sure each count is limited to no higher than 
the reference count.



More information about the Python-list mailing list