我试图按优势度(按百分比递减)对成分语句进行多层次排序。在
我使用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中最优雅的方法是什么。哦,还有另一个警告,因为我是有限的,我可以导入什么模块。如果它不是一个包含的模块,我可能无法访问它,因为我的环境。在
你可以用这样的发电机:
如果在将列表传递给函数之前只对列表排序一次,则可以进一步简化它。然后,您只需过滤项目,而不必对其进行多次排序:
^{pr2}$在Python-3.3+中,可以使用^{} 并使其更短:
一般注意事项:
我将您的} 。在
list
重命名为lst
,这样它就不会隐藏内置的^{您处理的是元组,但是通过名称来引用它们,所以也可以使用^{} 。这也允许您按属性引用项目:
^{4}$就我个人而言,我喜欢
namedtuple
s,但有些人不喜欢,你说你受你的导入的限制(它在标准库中,但无论如何),所以我只把它包括在这里。。。最后。在相关问题 更多 >
编程相关推荐