[Tutor] newB Q: extracting common elements from 2 lists

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Mon, 24 Jun 2002 10:20:34 -0700 (PDT)


On Mon, 24 Jun 2002, Andrei Kulakov wrote:

> > >>> xmap
> > {1: [1, 3, 5, 7, 9]}
> > >>> ymap
> > {1: [1, 2, 3, 4, 5]}
> >
> > what I want is to extract the common elements

[some text cut]

> > like:
> >
> > xymap[1] = xmap[1] *something magic here* ymap[1]



We can do some magic if you'd like.  *grin* Let me take Andrei's code
snippet:

> >>> a = [1, 3, 5, 7, 9]
> >>> b = [1, 2, 3, 4, 5]
> >>> ab = [x for x in a if x in b]
> >>> ab
> [1, 3, 5]
>
> Or as a loop:
> ab = []
> for x in a:
> 	if x in b:
> 		ab.append(x)



and mix it into a class that looks a little bit like a map:

###
class IntersectedMap:
    """Returns a map-like object that tries to intersect two maps
in Steven's data structure."""
    def __init__(self, map1, map2):
        self.map1, self.map2 = map1, map2

    def __getitem__(self, index):
        l1 = self.map1[index]
        l2 = self.map2[index]
        return intersection(l1, l2)


def intersection(a, b):
    """Returns the intersection between two lists."""
    ab = []
    for x in a:
        if x in b: ab.append(x)
    return ab
###


Let's see how this might work:

###
>>> xmap = {1 : [1, 3, 5, 7, 9]}
>>> ymap = {1 : [1, 2, 3, 4, 5]}
>>> xymap = IntersectedMap(xmap, ymap)
>>> xymap[1]
[1, 3, 5]
>>> xmap[1].append(2)
>>> xmap
{1: [1, 3, 5, 7, 9, 2]}
>>> xymap[1]
[1, 3, 5, 2]
###



Hope this helps!