我有一个类长方体:
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
但是,对我来说,这感觉有点笨拙。我之前尝试使用列表推导,但我无法让它们删除所有相交的多维数据集。
有更好的方法吗?
答案 0 :(得分:0)
假设您的交叉功能可以正常工作,我认为您可以使用itertools.combinations来执行此操作。
基本上,调用itertools.combinations(cubelist,2)将在cubelist中生成所有可能的Cub对。像
这样的东西for cube1, cube2 in itertools.combinations(cubelist, 2):
# I'm adding this since I'm not sure what happens when you remove elements as you go
if cube1 in cubelist and cube2 in cubelist:
if cube1.intersects(cube2):
cubelist.remove(cube2)