以下代码应该可以工作:
def resultHandler(extractedResult):
jsonList = []
for i in range(len(extractedResult) // 2):
jsonList.append({"Id": i})
for i in range(len(extractedResult)):
for j in range(len(jsonList)):
if jsonList[j]["Id"] == extractedResult[i]["Id"]:
if "title" in extractedResult[i]:
jsonList[j]["title"] = extractedResult[i]["title"];
else:
jsonList[j]["location"] = extractedResult[i]["location"];
return jsonList;
extractedResult = [{"Id": 0, "title":"example1"}, {"Id": 1, "title":"example2"}, {"Id": 0, "location":"example3"}, {"Id": 1, "location":"example4"}]
jsonList = resultHandler(extractedResult)
print(jsonList)
输出:
[{'Id': 0, 'title': 'example1', 'location': 'example3'}, {'Id': 1, 'title': 'example2', 'location': 'example4'}]
此代码首先填充
jsonList
Id值从0到长度的一半
extractedResult
(ID的数量也是如此)。
然后,对于每一本字典
提取结果
,我们在字典里找到了
jsonList
和匹配的ID。如果
提取结果
包含一个密钥,
"title"
,然后我们在
jsonList
.这同样适用于
"location"
.
我希望这有助于回答你的问题!如果您需要任何进一步的澄清或详细信息,请告诉我:)