我有一个类长方体:
class Cuboid:
#a rectangular solid
def __init__(self, (x0, y0, z0), (x1, y1, z1)):
self.z0 = min(z0,z1)
self.x0 = min(x0,x1)
self.y0 = min(y0,y1)
self.z1 = max(z0,z1)
self.x1 = max(x0,x1)
self.y1 = max(y0,y1)
self.start = (self.x0, self.y0, self.z0)
self.end = (self.x1, self.y1, self.z1)
def centre(self):
center_x = (self.x0 + self.x1)/2
center_y = (self.y0 + self.y1)/2
center_z = (self.z0 + self.z1)/2
return (center_x, center_y, center_z)
def intersects(self, other):
#returns true if this cuboid intersects with another one
if self == other:
return True
else:
return (
self.x0 <= other.x1
and self.x1 >= other.x0
and self.y0 <= other.y1
and self.y1 >= other.y0
and self.z0 <= other.z1
and self.z1 >= other.z0
)
我创建了一个包含十个随机坐标的立方体列表:
cubelist = []
for i in range(10):
cube = Cuboid((rand.randint(1,80), rand.randint(1,80), rand.randint(1,3)), (rand.randint(1,80), rand.randint(1,80), rand.randint(5,9)))
cubelist.append(cube)
我想要做的是获取这个列表并从中删除所有相交的立方体。(我可以在调用追加时检查相交,但我想看看我是否也可以这样做)
我能做的唯一方法是这样的:
def cube_untangler(cubelist)
cubelist1 = [x for x in cubelist]
cubelist2 = [x for x in cubelist]
for x in cubelist:
cubelist1.remove(x)
if any(x.intersects(y) for y in cubelist1):
cubelist2.remove(x)
return cubelist2
不过,这对我来说感觉有点笨拙。我之前尝试过使用列表推导,但我无法让它们删除所有相交的立方体。
有一个更好的方法吗?