Python - 计算 JSON 中值组合的出现次数
Python - Count occurrences of combination of values in JSON
我正在使用 python 来尝试解析 JSON
文件。与此类似question,我想统计文件中2个值的每个组合出现的次数:
示例JSON:
{
"first": "John",
"last": "Smith"
},
{
"first": "Adam",
"last": "Smith"
},
{
"first": "Adam",
"last": "Doe"
},
{
"first": "John",
"last": "Smith"
}
所需的输出将计算如下(不太关心格式更多关于计数值和相关元素):
{
"first": "John", "last": "Smith", "count": 2
},
{
"first": "Adam", "last": "Smith", "count": 1
},
{
"first": "Adam", "last": "Doe", "count": 1
}
我试过下面的方法,但它显然只计算唯一的“第一个”值,我无法找到一种方法将第二个属性“最后”视为
嗯。
import json
from json import load
from collections import Counter
f = open('/PathToFile')
data = load(f)
c = Counter(i ['first'] for i in data)
print(c)
您可以在计数器中计算元组(第一个,最后一个):
Counter((i['first'], i['last']) for i in data)
我正在使用 python 来尝试解析 JSON
文件。与此类似question,我想统计文件中2个值的每个组合出现的次数:
示例JSON:
{
"first": "John",
"last": "Smith"
},
{
"first": "Adam",
"last": "Smith"
},
{
"first": "Adam",
"last": "Doe"
},
{
"first": "John",
"last": "Smith"
}
所需的输出将计算如下(不太关心格式更多关于计数值和相关元素):
{
"first": "John", "last": "Smith", "count": 2
},
{
"first": "Adam", "last": "Smith", "count": 1
},
{
"first": "Adam", "last": "Doe", "count": 1
}
我试过下面的方法,但它显然只计算唯一的“第一个”值,我无法找到一种方法将第二个属性“最后”视为 嗯。
import json
from json import load
from collections import Counter
f = open('/PathToFile')
data = load(f)
c = Counter(i ['first'] for i in data)
print(c)
您可以在计数器中计算元组(第一个,最后一个):
Counter((i['first'], i['last']) for i in data)