Python在对象属性上设置交集

2024-10-03 11:13:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两套,每套都包含以下类别的对象:

class pointInfo:
    x = 0
    y = 0
    steps = 0

我想找到两个集合的交集,但只在x和y值上。 比如:

def findIntersections(pointInfoSet1, pointInfoSetwire2):
    return [pointInfo for pointInfo in pointInfoSet1 if pointInfo.x, pointInfo.y in pointInfoSet2]

我知道,如果在python中有两个集合,那么只需执行set1.intersection(set2),但在本例中这不起作用,因为我只想找到对象属性的某个子集在哪里是相同的,而不是相同的对象。提前谢谢


Tags: 对象inforreturnifdefsteps类别
1条回答
网友
1楼 · 发布于 2024-10-03 11:13:30

下面是一个解决方案,它使Point对象在其x和y属性上都是Hashable

class Point:
    def __init__(self, x=0, y=0, step=0):
        self.x = x
        self.y = y
        self.step = step
    def __eq__(self, other):
        if not isinstance(other, Point):
            return NotImplemented
        return (self.x, self.y) == (other.x, other.y)
    def __hash__(self):
        return hash((self.x, self.y))
    def __repr__(self):
        return "Point(x={0.x}, y={0.y}, step={0.step})".format(self)

然后我们可以将它们放在一组中,自然地获得交点:

{Point(1, 1, 1), Point(2, 2)} & {Point(1, 1, 2)}
# {Point(x=1, y=1, step=2)}

假设没有导线自身交叉,更好的解决方案可能是通过两条导线进行迭代,保持点到步长的dict,并输出每个交点处的步长总和:

from itertools import chain

def stepsToIntersections(wire1, wire2):
    seen = {}
    for point in chain(wire1, wire2):
        if point in seen:
            yield point.step + seen[point]
        else:
            seen[point] = point.step

closest = min(stepsToIntersections(wire1, wire2))

相关问题 更多 >