list comprehention

Peter Otten __peter__ at web.de
Thu Jan 19 18:41:08 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)
> 
> Any suggestions or comments?
 
sum(min(list.count(n), ref.count(n)) for n in set(ref))

Is that it?

Peter



More information about the Python-list mailing list