我有一个树结构,类似于: 公司 -> 部门 -> 角色 ->
我有一个像这样的三重循环结构:
for company in self.Companies():
cName = company.Name()
for dept in company.Departments():
dName = department.Name()
for role in dept.Roles():
rName = role.Name()
roleID = role.ID()
.Name() 函数返回部门名称,例如 Android-Sales。公司可以有零个或多个部门。
到目前为止,以上就是我所拥有的一切。我正在尝试开发这个,以便我可以获得列表列表: 理想情况下,这就是我想要的。如果重复,列表中的下一项应留空。或者它可能没有字段,在这种情况下也将其留空。
[
[“Google”、“Android 销售”、“营销人员”、“A123”],
['','Google-Play','开发者','A435'],
['','','测试仪','A125'],
['','','','A126'],
['我的小公司','','超级角色','A123'] ]
或者这也可以...
[
[“Google”、“Android 销售”、“营销人员”、“A123”],
['Google'、'Google-Play'、'开发者'、'A435'],
['Google','Google-Play','测试仪','A125'],
['Google','Google-Play','测试仪','A126'],
['我的小公司','','超级角色','A123'](这里“我的小公司”没有 > 部门。 ]
每个内部列表的长度应为 4。
尝试这样的事情:
tree = {"Google":{"Android":"yes", "Nexus":"no"}}
list_of_lists = []
def listbuilder(sub_tree, current_list):
for key in sub_tree:
if isinstance(sub_tree[key], dict):
listbuilder(sub_tree[key], current_list + [key])
else:
list_of_lists.append(current_list + [key] + [sub_tree[key]])
listbuilder(tree,[])
print str(list_of_lists)
输出:
[['Google', 'Nexus', 'no'], ['Google', 'Android', 'yes']]
不久前,我需要以结构化方式将 JSON 文件插入数据库。根据 @Gillespie 描述的解决方案,我能够将文件层次结构转换为列表列表。
以下脚本期望读取一个 JSON 文件,其项目列表最初由父键“value”标识。这是
data.json
文件的简单示例。
{
"value":
[
{
"A": 0,
"B": 1,
"C": 2
},
{
"C": {
"E": 3,
"F": 4
},
"D": [
{
"G": 5
},
{
"H": 6
}
]
}
]
}
以下脚本读取 JSON 文件并将其转换为要插入数据库的元组列表。请记住在数据库中创建表和列之前删除特殊字符。
import json
def dict_to_list(sub_tree: dict, current_list: [str], items_list: [[str]]) -> [[str]]:
try: # Tree branches.
for key in sub_tree:
if isinstance(sub_tree[key], list):
for sub_item in sub_tree[key]:
dict_to_list(sub_tree=sub_item, current_list=current_list + [key], items_list=items_list)
elif isinstance(sub_tree[key], dict):
dict_to_list(sub_tree=sub_tree[key], current_list=current_list + [key], items_list=items_list)
else:
items_list.append(current_list + [key] + [sub_tree[key]])
except: # Tree leaf.
items_list.append(current_list + [str(sub_tree)])
return items_list
def json_data_to_samples_list(json_data: dict, data_key: str = 'value', column_sep: str = "_") -> [[(str, str)]]:
samples_list = []
for parent in json_data[data_key]:
column_value_tuples = []
for child in dict_to_list(sub_tree=parent, current_list=[], items_list=[]):
column = column_sep.join(child[:-1])
value = child[-1]
column_value_tuples.append((column, value))
samples_list.append(column_value_tuples)
return samples_list
def main() -> None:
json_file_path = "data.json"
with open(json_file_path, mode="r", encoding="utf-8") as file:
json_data = json.load(file)
samples_list = json_data_to_samples_list(json_data=json_data)
print(f"\nExtracted {len(samples_list)} items from the JSON file:")
for idx, parent in enumerate(samples_list):
print(f"\n>>>>> Child #{idx}:")
for child in parent:
print(f"\t\t{child}")
print()
if __name__ == '__main__':
main()
Extracted 2 items from the JSON file:
>>>>> Child #0:
('A', 0)
('B', 1)
('C', 2)
>>>>> Child #1:
('C_E', 3)
('C_F', 4)
('D_G', 5)
('D_H', 6)