python中包含对象类型的两个列表的交集

Ram*_*ack 1 python tuples intersection list

如何在Python中找到包含浮点值元组的两个列表的交集?例如:

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)]
Run Code Online (Sandbox Code Playgroud)

我需要

A intersection B = [(1.1,2.2),(3.3,4.4)]
Run Code Online (Sandbox Code Playgroud)

更新:

我的错。感谢您的回复,但我的理解存在误解。

问题应该是

例如:

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)]
Run Code Online (Sandbox Code Playgroud)

我需要

A intersection B = [Point(1.1,2.2),Point(3.3,4.4)]
Run Code Online (Sandbox Code Playgroud)

其中 Point 是我的 python 类,包含两个浮点变量,如图所示

class Point:
    def __init__(self, a_, b_):
        self.a = a_
        self.b = b_
Run Code Online (Sandbox Code Playgroud)

Pad*_*ham 5

如果顺序无关紧要,请使用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)])
Run Code Online (Sandbox Code Playgroud)

或者将 B 设为集合并迭代 A 并保留公共元素:

st = set(B)

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

[(1.1, 2.2), (3.3, 4.4)]
Run Code Online (Sandbox Code Playgroud)

如果您正在寻找具有相同属性值的对象:

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])
Run Code Online (Sandbox Code Playgroud)

或者在你的类中创建一个哈希方法:

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))
Run Code Online (Sandbox Code Playgroud)