在python中包含Object类型的两个列表的交集

时间:2015-04-17 15:15:31

标签: python list tuples intersection

如何在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)]

我需要

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

更新

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

问题应该是

例如:

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)]

我需要

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

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

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

1 个答案:

答案 0 :(得分:4)

如果订单无关紧要,请使用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)])

或者使B成为一组并迭代A保持共同元素:

st = set(B)

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

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

如果您要查找具有相同属性值的对象:

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])

或者在班级中创建哈希方法:

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))