【发布时间】:2014-01-09 15:55:57
【问题描述】:
我正在使用 Python 字典 (product_dict) 来表示产品及其所有子部分的层次结构。 dict 的键是唯一 ID (UUID),值是包含有关这些部分的所有信息的 Class 对象,包括:
part.name # A string, containing the actual name of a component
part.idCode # UUID of component
part.parent # UUID of parent component
part.children # List of UUIDs of child components
part.tier # An integer that specifies its tier/level within the hierarchy
现在为了有序地输出数据,我希望按层次和字母顺序对部分进行排序。对于使用树结构的分层排序,我发现这个问题的答案非常适合打印:Sorting data hierarchically。为了让这个示例与我的数据结构一起使用,我做了一些细微的修改:
class Node:
def __init__(self, article):
self.article = article
self.children = []
self.parent = None
self.name = None
def printer(self, level=0):
print ('{}{}'.format('\t' * level, self.name))
for child in self.children:
child.printer(level + 1)
class Tree:
def __init__(self):
self.nodes = {}
def push(self, article, parent, name):
if parent not in self.nodes:
self.nodes[parent] = Node(parent)
if article not in self.nodes:
self.nodes[article] = Node(article)
if parent == article:
return
self.nodes[article].name = name
self.nodes[article].parent = self.nodes[parent]
self.nodes[parent].children.append(self.nodes[article])
@property
def roots(self):
return (x for x in self.nodes.values() if not x.parent)
t = Tree()
for idCode, part in product_dict.iteritems():
t.push(idCode, part.parent, part.name)
for node in t.roots:
node.printer()
考虑到我的产品是飞机的例子,现在的输出如下所示(实际顺序不同):
Aircraft
Systems
Subsystem 2
Subsystem 1
Subsubsystem 1.1
Engines
Airframe
Section 2
Section 1
Section 4
Section 3
但是,由于我现阶段对 Python 的了解有限,我正在努力将字母排序添加到此例程中(基于 part.name 字符串)。我了解树是如何构建的,但我不掌握打印例程,因此无法判断在哪里添加字母排序例程。
对于给定的示例,我想要的输出应该是:
Aircraft
Airframe
Section 1
Section 2
Section 3
Section 4
Engines
Systems
Subsystem 1
Subsubsystem 1.1
Subsystem 2
非常感谢任何帮助。我不坚持上面给出的分层排序方法,所以我对完全不同的方法持开放态度。
【问题讨论】:
标签: python sorting python-2.7 dictionary hierarchical-data