用层次ord按百分比递减对元组列表排序

2024-09-29 00:20:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图按优势度(按百分比递减)对成分语句进行多层次排序。在

我使用Python,有一个元组列表,每个元组都有以下变量:(component、percentage、childID、parentID)。在

它来自类似这样的数据,数据可以按任何顺序输入。下面的列是成分/子成分、百分比、childID、parentID。在

#Ing1   30%             1   0
#---Sub1    30%         2   1
#---Sub2    60%         3   1
#------Sub3     15%     4   3
#------Sub4     85%     5   3
#---Sub5    10%         6   1
#Ing2   10%             7   0
#Ing3   60%             5   0

我的现有代码在如下列表中输出给我(输入的顺序):

^{pr2}$

我需要做的是排序这个列表下降购买百分比,同时保持层次结构从低层向上完整。因此,第三级配料(Sub3、Sub4)首先,然后是下一级,然后是顶层。
子级别需要与其父级进行排序。在

因此,对于上面的示例,我需要按以下顺序输出:

> #Ing3 60%             5   0
> #Ing1 30%             1   0
> #---Sub2  60%         3   1
> #------Sub4   85%     5   3
> #------Sub3   15%     4   3
> #---Sub1  30%         2   1
> #---Sub5  10%         6   1
> #Ing2 10%             7   0

所以清单应该是这样的:

list = [(Ing3,60,5,0),(Ing1,30,1,0),(Sub2,60,3,1),(Sub4,85,5,3),(Sub3,15,4,3),(Sub1,30,2,1),(Sub5,10,6,1),(Ing2,10,7,0)]

在Python中最优雅的方法是什么。哦,还有另一个警告,因为我是有限的,我可以导入什么模块。如果它不是一个包含的模块,我可能无法访问它,因为我的环境。在


Tags: 列表排序顺序元组百分比成分sub1sub2
1条回答
网友
1楼 · 发布于 2024-09-29 00:20:58

你可以用这样的发电机:

lst = [('Ing1',30,1,0),
       ('Sub1',30,2,1),
       ('Sub2',60,3,1),
       ('Sub3',15,4,3),
       ('Sub4',85,5,3),
       ('Sub5',10,6,1),
       ('Ing2',10,7,0),
       ('Ing3',60,5,0)]

def sort_hierarchical(lst, parent=0):
    # sort the current layer (excluding all other elements) by the second element
    res = sorted([i for i in lst if i[3] == parent], key=lambda x: x[1], reverse=True)
    for item in res:
        yield item
        # recurse for all childs of this item
        for subitem in sort_hierarchical(lst, parent=item[2]):
            yield subitem

>>> list(sort_hierarchical(lst))
[('Ing3', 60, 5, 0),
 ('Ing1', 30, 1, 0),
 ('Sub2', 60, 3, 1),
 ('Sub4', 85, 5, 3),
 ('Sub3', 15, 4, 3),
 ('Sub1', 30, 2, 1),
 ('Sub5', 10, 6, 1),
 ('Ing2', 10, 7, 0)]

如果在将列表传递给函数之前只对列表排序一次,则可以进一步简化它。然后,您只需过滤项目,而不必对其进行多次排序:

^{pr2}$

在Python-3.3+中,可以使用^{}并使其更短:

def return_hierarchical(lst, parent=0):
    for item in (i for i in lst if i[3] == parent):
        yield item
        yield from return_hierarchical(lst, parent=item[2])

一般注意事项:

我将您的list重命名为lst,这样它就不会隐藏内置的^{}。在

您处理的是元组,但是通过名称来引用它们,所以也可以使用^{}。这也允许您按属性引用项目:

^{4}$

就我个人而言,我喜欢namedtuples,但有些人不喜欢,你说你受你的导入的限制(它在标准库中,但无论如何),所以我只把它包括在这里。。。最后。在

相关问题 更多 >