86 lines
2.5 KiB
Markdown
86 lines
2.5 KiB
Markdown
```python
|
||
def tree_dict_to_table_data(tree: Dict) -> List[List[str]]:
|
||
"""
|
||
将树状字典转换为二维表格数据
|
||
|
||
参数:
|
||
tree: 树状字典,结构为dict[dict[...[list]]]
|
||
|
||
返回:
|
||
二维列表表示的表格数据
|
||
"""
|
||
if not tree:
|
||
return []
|
||
|
||
# 首先确定树的深度
|
||
depth = 0
|
||
current = tree
|
||
while isinstance(current, dict):
|
||
depth += 1
|
||
# 获取第一个子节点来继续探测深度
|
||
if current:
|
||
current = next(iter(current.values()))
|
||
else:
|
||
break
|
||
|
||
# 收集所有路径和叶子节点
|
||
paths = []
|
||
|
||
def traverse(node, current_path):
|
||
if isinstance(node, dict):
|
||
for key, value in node.items():
|
||
traverse(value, current_path + [str(key)])
|
||
elif isinstance(node, list):
|
||
paths.append((current_path, node))
|
||
else:
|
||
paths.append((current_path, [str(node)]))
|
||
|
||
traverse(tree, [])
|
||
|
||
# 确定最大深度(处理可能的不平衡树)
|
||
max_depth = max(len(path) for path, _ in paths) if paths else 0
|
||
max_leaf_length = max(len(leaf) for _, leaf in paths) if paths else 0
|
||
|
||
# 填充路径到最大深度
|
||
filled_paths = []
|
||
for path, leaf in paths:
|
||
# 填充路径
|
||
filled_path = path.copy()
|
||
while len(filled_path) < max_depth:
|
||
filled_path.append("") # 用空字符串填充不足的深度
|
||
|
||
# 填充叶子节点
|
||
filled_leaf = leaf.copy()
|
||
while len(filled_leaf) < max_leaf_length:
|
||
filled_leaf.append("") # 用空字符串填充不足的叶子长度
|
||
|
||
filled_paths.append((filled_path, filled_leaf))
|
||
|
||
# 构建表格数据
|
||
table_data = []
|
||
|
||
# 添加路径部分的行
|
||
for i in range(max_depth):
|
||
row = []
|
||
for path, leaf in filled_paths:
|
||
row.append(path[i])
|
||
table_data.append(row)
|
||
|
||
# 添加叶子部分的行
|
||
for i in range(max_leaf_length):
|
||
row = []
|
||
for path, leaf in filled_paths:
|
||
row.append(leaf[i] if i < len(leaf) else "")
|
||
table_data.append(row)
|
||
|
||
# 转置表格,使每个路径+叶子成为一列
|
||
if table_data:
|
||
# 获取最大列数
|
||
max_cols = max(len(row) for row in table_data) if table_data else 0
|
||
# 统一每行的列数
|
||
table_data = [row + [""] * (max_cols - len(row)) for row in table_data]
|
||
# 转置
|
||
table_data = list(map(list, zip(*table_data)))
|
||
|
||
return table_data
|
||
``` |