目录递归排版:
class to_dict:
def __init__(self, lst):
self.lst = sorted(lst)
self.min_len = min(len(i) for i in self.lst)
self.dictdata = {}
def gen_dict(self, idx):
return {'id': f'{idx}', 'subject': {}}
def add_to_dict(self, idx, dict1, sub_dict):
if len(idx) == self.min_len:
sub_dict[idx] = dict1
return
prefix = next((s for s in sub_dict.keys() if idx.startswith(s)), None)
if prefix is None:
sub_dict[idx] = dict1
else:
self.add_to_dict(idx, dict1, sub_dict[prefix]['subject'])
def main(self):
for idx in self.lst:
self.add_to_dict(idx, self.gen_dict(idx), self.dictdata)
return self.dictdata
td = to_dict(lst)
print(td.main())