如何打印 python 中总和最高的对象嵌套列表

How to print a nested list of objects with the highest sum in python

我仍在学习 python 并且我在处理对象方面仍然遇到困难,我正在尝试编写一个程序来计算项目中一组活动的关键路径,我已经能够获得活动的关键路径,它们存储为嵌套对象列表,每个对象都有不同的属性,如 id、前身和持续时间,我遇到的问题是打印出结果正确地,我想打印出持续时间最长的路径和给出该值的路径本身

class criticalPath:

    def __init__(self):
        '''
        Initialize all the variables we're going to use to calculate the critical path
        '''
        self.id = None
        self.pred = tuple()
        self.dur = None
        self.est = None
        self.lst = None
        #list to store all the objects
        self.all_objects = list()

    def set_properties(self, name, predecessor, duration):
        self.id = name
        self.pred = tuple(predecessor)
        self.dur = duration


def main():
    #starting_nodes = list()
    object_list = list()

    A = criticalPath()
    A.set_properties('A', '0', 3)

    B = criticalPath()
    B.set_properties('B', '0', 6)

    C = criticalPath()
    C.set_properties('C', 'A', 1)

    D = criticalPath()
    D.set_properties('D', 'B', 4)



    tmp_list = list()
    tmp_list.append(A)
    tmp_list.append(C)
    object_list.append(tmp_list)

    tmp_list = list()
    tmp_list.append(B)
    tmp_list.append(D)
    object_list.append(tmp_list)


    print('The total duration of the project is {}'.format(max([sum([node.dur for node in object]) for object in object_list])))
    #print(max(object_list.id, key=sum(object_list.dur)))


if __name__ == '__main__': main()

我已经能够打印出总持续时间,在本例中为 10,我注释掉的最后一行是我最后一次尝试根据对象的个人持续时间比较 object_lists 中的对象 ID是每个对象的 属性 'id' 和 'dur',所以基本上我想得到这样的输出

项目的关键路径为B==>D,项目总工期为10

class criticalPath:

    def __init__(self):
        '''
        Initialize all the variables we're going to use to calculate the critical path
        '''
        self.id = None
        self.pred = tuple()
        self.dur = None
        self.est = None
        self.lst = None
        #list to store all the objects
        self.all_objects = list()

    def set_properties(self, name, predecessor, duration):
        self.id = name
        self.pred = tuple(predecessor)
        self.dur = duration


def main():
    #starting_nodes = list()
    object_list = list()

    A = criticalPath()
    A.set_properties('A', '0', 3)

    B = criticalPath()
    B.set_properties('B', '0', 6)

    C = criticalPath()
    C.set_properties('C', 'A', 1)

    D = criticalPath()
    D.set_properties('D', 'B', 4)

    tmp_list = list()
    tmp_list.append(A)
    tmp_list.append(C)
    object_list.append(tmp_list)

    tmp_list = list()
    tmp_list.append(B)
    tmp_list.append(D)
    object_list.append(tmp_list)

    print(object_list)

    print('The total duration of the project is {}'.format(max([sum([node.dur for node in object]) for object in object_list])))
    print([path.id for path in max(object_list, key=lambda ls: sum(obj.dur for obj in ls))])


if __name__ == '__main__': main()