I am trying to sort and make an html table from a python list (list comes from database):
[('222', 'Workroom', '111'),
('333', 'Setup Part', '222'),
('444', 'Scale', '222'),
('666', 'Workroom', ''),
('888', 'Setup Part', '777'),
('777', 'Workroom', '666'),
('555', 'Workroom', '111'),
('111', 'Workroom', '')]
based on their hierarchy. The first item in each tuple represents its ID, the second one represents a description and the third represents its "parent". How could I make a program that organizes it in a hierarchical form in an html table?
this is what I mean by hierarchical form and an example of what I would like to do with the data
Ok , if we say that the parent is always bigger than the children /because it is above them/ we write:
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
which gives:
[('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')]
Now , just to know the levels , we can nest lists:
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')]]]]]]]]
Now , to make this html is an easy job:
just , put each element in <td> </td>
each list you find,
perhaps check if the length is 3 item is found
==> close the <td>
tags!