我有一个类似于以下内容的json文件:
[
{
"category1":"0120391123123"
},
[
{
"subcategory":"0120391123123"
},
[
{
"subsubcategory":"019301948109"
},
[
{
"subsubsubcategory":"013904123908"
},
[
{
"subsubsubsubcategory":"019341823908"
}
]
]
]
],
[
{
"subcategory2":"0934810923801"
},
[
{
"subsubcategory2":"09341829308123"
}
]
],
[
{
"category2":"1309183912309"
},
[
{
"subcategory":"10293182094"
}
]
]
]
我还想在原始列表中找到一个类别列表。如果该类别存在于CategoriesToFind中,我也想找到所有子类别并返回它们。
categoriesToFind = ['019301948109', '1309183912309']
finalCategories = []
def findCategories(currentList, isFirstIteration):
for x in currentList:
if type(x) is dict and (next(iter(x.values())) in categoriesToFind or not isFirstIteration):
finalCategories.append(next(iter(x.values())))
if len(currentList) < currentList.index(x) + 1:
findCategories(currentList[currentList.index(x) + 1], False)
findCategories(data, True)
我希望finalCategories包含以下内容:
['019301948109', '013904123908', '019341823908', '1309183912309', '10293182094']
答案 0 :(得分:3)
您可以将递归与生成器一起使用:
['019301948109', '013904123908', '019341823908', '1309183912309', '10293182094']
输出:
INSERT INTO table_name (ID,Name,Location)
VALUES (1232346, 'Bob', 'France')