如何按层次结构对列表进行排序并在 python 中生成 html table?

how to sort a list by hierarchy and make an html table out of it in python?

我正在尝试从 python 列表(列表来自数据库)中排序并制作 html table:

[('222', 'Workroom', '111'),
 ('333', 'Setup Part', '222'),
 ('444', 'Scale', '222'),
 ('666', 'Workroom', ''),
 ('888', 'Setup Part', '777'),
 ('777', 'Workroom', '666'),
 ('555', 'Workroom', '111'),
 ('111', 'Workroom', '')]

基于他们的层次结构。每个元组中的第一项代表其 ID,第二项代表描述,第三项代表其 "parent"。我怎样才能制作一个程序,以 html table 的分层形式组织它?

这就是我所说的分层形式以及我想对数据进行的操作的示例

好吧,如果按照层次顺序,你的意思是按元组的第一个值排序,你可以只使用 python 中的命令 sorted()。这将是输出:

[('111', 'Workroom', ''), ('222', 'Workroom', '111'), ('333', 'Setup Part', '222'), ('444', 'Scale', '222'), ('555', 'Workroom', '111'), ('666', 'Workroom', ''), ('777', 'Workroom', '666'), ('888', 'Setup Part', '777')]

现在你可以用 python 创建一个 html table:

head = '\n<tr>\n\t<th>A</th>\n\t<th>B</th>\n\t<th>C</th>\n</tr>\n'
body = ''
for row in sorted(list_of_tuples):
    body += '<tr>\n\t<td>{}</td>\n\t<td>{}</td>\n\t<td>{}</td>\n</tr>\n'.format(row[0], row[1], row[2])

table = '<table>' + head + body + '</table>'

好的,如果我们说 parent 总是 大于 children /因为它在他们之上/我们写道:

a = [('222', 'Workroom', '111'),
('333', 'Setup Part', '222'),
('444', 'Scale', '222'),
('666', 'Workroom', ''),
('888', 'Setup Part', '777'),
('777', 'Workroom', '666'),
('555', 'Workroom', '111'),
('111', 'Workroom', '')]

for i,s in enumerate(a):
    if len(s[2])==0:
        a[i] =(s[0],s[1],'000')
        # just to avoid int error

v = sorted(a, key=lambda x: x[0]+str(int(x[0])-int(x[2])))
print v

给出:

[('111', 'Workroom', '000'),
('222', 'Workroom', '111'),
('333', 'Setup Part', '222'),
('444', 'Scale', '222'),
('555', 'Workroom', '111'),
('666', 'Workroom', '000'),
('777', 'Workroom', '666'),
('888', 'Setup Part', '777')]

现在,为了了解级别,我们可以嵌套列表:

z = [];

for r in v:
    x = r[:];
    for n in range(int(r[2][0])):
        x = list([x])
    z.append(x)

# Result:

[('111', 'Workroom', '000'),
 [('222', 'Workroom', '111')],
 [[('333', 'Setup Part', '222')]],
 [[('444', 'Scale', '222')]],
 [('555', 'Workroom', '111')],
 ('666', 'Workroom', '000'),
 [[[[[[('777', 'Workroom', '666')]]]]]],
 [[[[[[[('888', 'Setup Part', '777')]]]]]]]]

现在,制作这个 html 很容易:

只是,将每个元素放在 <td> </td> 你找到的每个列表中,

也许检查长度是否为 3 找到项目 ==> 关闭 <td> 标签!