Python基于属性的有序列表

时间:2019-02-21 18:32:03

标签: python topological-sort

我有以下要根据依赖关系排序的对象列表。首先,将没有依赖关系的对象首先添加到列表中,然后对添加的第一个批次具有依赖关系的批处理,依此类推,直到从列表中删除所有项目为止。

pp = [
    {"name": 'pipeline13', "deps": 'pipeline11' },
    {"name": 'pipeline1', "deps": 'pipeline4' },
    {"name": 'pipeline4'},
    {"name": 'pipeline2', "deps": 'pipeline4'},
    {"name": 'pipeline3'}, 
    {"name": 'pipeline5'},
    {"name": 'pipeline6', "deps": 'pipeline2'},
    {"name": 'pipeline7'},
    {"name": 'pipeline8', "deps": 'pipeline2'},
    {"name": 'pipeline9', "deps": 'pipeline3'},
    {"name": 'pipeline10', "deps": 'pipeline1' },
    {"name": 'pipeline11', "deps": 'pipeline10' }
]

当前,我有下面的代码可以工作,但是它不是可扩展的,也不是非常Pythonic。

output = []
output_stage_1 = []
output_stage_2 = []
output_stage_3 = []
output_stage_4 = []
output_stage_5 = []


while pp:
    for p in pp:
        if not p.get('deps'):
            output.append(p)
            pp.remove(p)


        if p.get('deps') in [i.get('name') for i in output]:
            output_stage_1.append(p)
            pp.remove(p)


        if p.get('deps') in [i.get('name') for i in output_stage_1]:
            output_stage_2.append(p)
            pp.remove(p)


        if p.get('deps') in [i.get('name') for i in output_stage_2]:
            output_stage_3.append(p)
            pp.remove(p)


        if p.get('deps') in [i.get('name') for i in output_stage_3]:
            output_stage_4.append(p)
            pp.remove(p)


        if p.get('deps') in [i.get('name') for i in output_stage_4]:
            output_stage_5.append(p)
            pp.remove(p)



print(output + output_stage_1 + output_stage_2 + output_stage_3 + output_stage_4 + output_stage_5)

2 个答案:

答案 0 :(得分:4)

  

我想根据依赖关系进行排序

这称为this article

以下一些资源可以向您展示如何做或为您完成工作:

答案 1 :(得分:1)

您可以这样做:

newMessage.setMessageData({
    [winnerId]: {
        "status": "win",
        "choice": playerData[winnerId]["currentChoice"],
        "newScore": playerData[winnerId]["score"]
    },
    [loserId]: {
        "status": "lost",
        "choice": playerData[loserId]["currentChoice"],
        "newScore": playerData[loserId]["score"]
    }
});

请注意,我并未对其进行优化,因此在处理大型数据集时可能会有点慢。

[编辑]这是一个优化的版本:

ordered = [ item["name"] for item in pp if "deps" not in item ]
while len(ordered) < len(pp):
    for item in pp:
        if "deps" not in item : continue
        if item["name"] not in ordered and item["deps"] in ordered:
            ordered.append(item["name"])