Ram's stack
Ram's stack

Reputation: 307

Intersection of two lists containing Object types in python

How to find the intersection of two lists containing tuples of float values in Python? For example:

A = [(1.1,2.2),(3.3,4.4),(5.5,6.6)]
B = [(1.1,2.2),(7.7,8.8),(3.3,4.4)]

I need

A intersection B = [(1.1,2.2),(3.3,4.4)]

Update:

My bad. Thanks for the response but I there was a misconception in my understanding.

The question should be

For example:

A = [Point(1.1,2.2),Point(3.3,4.4),Point(5.5,6.6)]
B = [Point(1.1,2.2),Point(7.7,8.8),Point(3.3,4.4)]

I need

A intersection B = [Point(1.1,2.2),Point(3.3,4.4)]

where Point is my python class containing two float variables as shown

class Point:
    def __init__(self, a_, b_):
        self.a = a_
        self.b = b_

Upvotes: 1

Views: 4284

Answers (2)

sariDon
sariDon

Reputation: 7981

Another solution:

Intersect my_list_01 and my_list_02, and store the result in intersected_list

intersected_list= [item for item in my_list_01 if item in my_list_02]

Upvotes: 0

Padraic Cunningham
Padraic Cunningham

Reputation: 180481

If order does not matter use set.intersection:

A = [(1.1,2.2),(3.3,4.4),(5.5,6.6)]
B = [(1.1,2.2),(7.7,8.8),(3.3,4.4)]

print(set(A).intersection(B))
set([(3.3, 4.4), (1.1, 2.2)])

Or make B a set and iterate over A keeping common elements:

st = set(B)

print([ele for ele in A if ele in st ])

[(1.1, 2.2), (3.3, 4.4)]

If you are looking for objects with the same attribute values:

A = [Point(1.1,2.2),Point(3.3,4.4),Point(5.5,6.6)]
B = [Point(1.1,2.2),Point(7.7,8.8),Point(3.3,4.4)]


st = set((p.a,p.b) for p in B)

print([p for p in A if (p.a,p.b) in st])

Or create a hash method in your class:

class Point(object):
    def __init__(self, a_, b_):
        self.a = a_
        self.b = b_

    def __hash__(self):
        return hash((self.a, self.b))

    def __eq__(self, other):
        return self.a, self.b == other.a,other.b

    def __ne__(self, other):
        return not self.__eq__(other)

A = [Point(1.1,2.2),Point(3.3,4.4),Point(5.5,6.6)]
B = [Point(1.1,2.2),Point(7.7,8.8),Point(3.3,4.4)]


print(set(A).intersection(B))

Upvotes: 5

Related Questions