1

我有一个类长方体:

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

不过,这对我来说感觉有点笨拙。我之前尝试过使用列表推导,但我无法让它们删除所有相交的立方体。

有一个更好的方法吗?

4

1 回答 1

0

假设您的交集功能按您的意愿工作,我认为您可以使用itertools.combinations来执行此操作。

本质上,调用 itertools.combinations(cubelist, 2) 将在 cubelist 中生成所有可能的小熊对。所以像

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)
于 2013-10-21T19:22:24.677 回答