list comprehention
bonono at gmail.com
bonono at gmail.com
Thu Jan 19 12:17:43 EST 2006
Tim Chase 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)
>
> It sounds like you're looking for "set" operations: (using "ell"
> for clarity)
>
> >>> from sets import Set
> >>> a = [2,2,4,1,1]
> >>> b = [2,3,4,5,3]
> >>> setA = Set(a)
> >>> setB = Set(b)
> >>> results = setA.intersection(setB)
> >>> results
> Set([2,4])
> >>> intersection = [x for x in results]
> >>> intersection
> [2,4]
>
>
won't set remove duplicates which he wants to preserve ? He is not just
looking for the 'values' that is in common, but the occurence as well,
if I understand the requirement correctly.
I would just build a dict with the value as the key and occurence as
the value then loop the list and lookup.
More information about the Python-list
mailing list