【发布时间】:2020-10-09 02:32:25
【问题描述】:
以下是 4 个 JSON 文件:
- 3 个 JSON 文件有 3 个关键字段:名称、评级和年份
- 1 JSON 只有 2 个关键字段:名称、评级(无年份)
[
{
"name": "Apple",
"year": "2014",
"rating": "21"
},
{
"name": "Pear",
"year": "2003",
"rating": ""
},
{
"name": "Pineapple",
"year": "1967",
"rating": "60"
},
]
[
{
"name": "Pineapple",
"year": "1967",
"rating": "5.7"
},
{
"name": "Apple",
"year": "1915",
"rating": "2.3"
},
{
"name": "Apple",
"year": "2014",
"rating": "3.7"
}
]
[
{
"name": "Apple",
"year": "2014",
"rating": "2.55"
}
]
[
{
"name": "APPLE",
"rating": "+4"
},
{
"name": "LEMON",
"rating": "+3"
}
]
当您在所有 4 个文件中搜索“Apple”时,您希望返回 1 个名称、1 个年份和 4 个评级:
name: Apple (closest match to search term across all 4 files)
year: 2014 (the MOST COMMON year for Apple across first 3 JSONs)
rating: 21 (from JSON1)
3.7 (from JSON2)
2.55 (from JSON3)
+4 (from JSON4)
现在假设 JSON3(或任何 JSON)与“名称:Apple”不匹配。在这种情况下,改为返回以下内容。假设在至少一个文件中至少有一个匹配项。
name: Apple (closest match to search term across all 4 files)
year: 2014 (the MOST COMMON year for Apple across first 3 JSONs)
rating: 21 (from JSON1)
3.7 (from JSON2)
Not Found (from JSON3)
+4 (from JSON4)
如何在 Python 中获得此输出?
这个问题和Python - Getting the intersection of two Json-Files中的示例代码类似,除了有4个文件,1个文件缺少year键,我们不需要的交集评级键的值。
这是我目前所拥有的,仅针对上面的两组 JSON:
import json
with open('1.json', 'r') as f:
json1 = json.load(f)
with open('2.json', 'r') as f:
json2 = json.load(f)
json2[0]['name'] = list(set(json2[0]['name']) - set(json1[0]['name']))
print(json.dumps(json2, indent=2))
我从中获得了输出,但它与我想要实现的目标不符。例如,这是输出的一部分:
{
"name": [
"a",
"n",
"i",
"P"
],
"year": "1967",
"rating": "5.7"
},
【问题讨论】:
-
您想要的输出有点抽象。你能根据输出的确切数据结构来指定吗?
标签: python json set-intersection