Python在对象属性上设置交集
我有两套,每套都包含以下类别的对象:Python在对象属性上设置交集,python,set,Python,Set,我有两套,每套都包含以下类别的对象: 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 pointInfoSet
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),但在本例中这不起作用,因为我只想找到对象属性的某个子集在哪里是相同的,而不是相同的对象。提前谢谢 这里有一个解决方案,可以使
点
对象在其x和y属性上可散列:
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))
pointInfo
对象是否仅在其x
和y
上更一般地相等?你可以写\uuuu eq\uuuuu
和\uuuuu hash\uuuuuu
方法来反映这一点,然后设置交点将正常工作。是的,基本上我有两个‘wire’,它们是一组点,我在沿着布线的同时,试图找到距离0,0最小的交点。所以x和y坐标有大约30个交点,但步长永远不相等。所以我只是想根据x和y的值进行比较