繁体   English   中英

Python,按最低子对象属性对对象列表进行排序

[英]Python, sort a list of objects by lowest sub-object attribute

我正在尝试实现曲面和点的深度排序,但是不确定如何执行。 我有一个Point类,它基本上包含x,y,z坐标,这些坐标用于定义圆的中心点,线的末端和曲面的角(三边形和四边形),所以我们有:

class Point(object):
    def __init__(self, x, y z):
        self.x = x
        self.y = y
        self.z = z

class Circle(object):
    def __init__(self, center, radius):
        #center is a point
        self.point_array = [center]
        self.radius = radius

class Line(object):
    def __init__(self, pos1, pos2):
        #pos1, pos2 are points
        self.point_array = [pos1, pos2]

class Tri(object):
    def __init__(self, pos1, pos2, pos3):
        #pos's are Points
        self.point_array = [pos1, pos2, pos3]

class Quad(object):
    def __init__(self, pos1, pos2, pos3, pos4):
        #you get the idea by now...
        self.point_array = [point1, point2, point3, point4]

现在,我将剔除那些不可见的对象,并将对象附加到列表中,以绘制到屏幕上。 我现在需要做的是按照每个对象的最低Z坐标对对象列表进行排序,但是我不确定如何进行此操作。

创建一个排序函数,以提取每个对象的最低z坐标:

def lowest_z(obj):
    return min(p.z for p in obj.point_array)

sorted(list_of_objects, key=lowest_z)

您当然可以使用lambda函数来内联该函数:

sorted(list_of_objects, key=lambda o: min(p.z for p in o.point_array))

假设您要排序的列表中没有Point对象,只有QuadTriLineCircle对象。

向您的对象添加返回最低z坐标的方法可能会有所帮助; 这样,您可以根据对象的类型调整如何确定该点; 这样,只有半径和中心点的Cicle类仍然可以基于该信息来计算最小值z

class Shape(object):
    # subclasses must provide a point_array instance attribute
    @property
    def lowest_z(self):
        return min(p.z for p in self.point_array)

class Line(Shape):
    def __init__(self, pos1, pos2):
        #pos1, pos2 are points
        self.point_array = [pos1, pos2]

class Circle(Shape):
    def __init__(self, center, radius):
        #center is a point
        self.point_array = [center]
        self.radius = radius

    @property
    def lowest_z(self):
        return self.point_array[0].z - self.radius

# etc.

然后按point_array属性排序:

sorted(list_of_objects, key=lambda o: o.lowest_z)

或者,使用operator.attrgetter()

from operator import attrgetter

sorted(list_of_objects, key=attrgetter('lowest_z'))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM