[英]Python - Count occurrences of combination of values in JSON
I'm using python to try and parse a JSON
file.我正在使用 python 来尝试解析
JSON
文件。 Similar to this question , I want to count the number of occurrences for each combination of 2 values in the file:与这个问题类似,我想计算文件中 2 个值的每个组合的出现次数:
Example JSON:示例 JSON:
{
"first": "John",
"last": "Smith"
},
{
"first": "Adam",
"last": "Smith"
},
{
"first": "Adam",
"last": "Doe"
},
{
"first": "John",
"last": "Smith"
}
Desired Output would calculate something like this (less concerned about format more about count values and associated elements):期望的 Output 会计算这样的东西(不太关心格式更多关于计数值和相关元素):
{
"first": "John", "last": "Smith", "count": 2
},
{
"first": "Adam", "last": "Smith", "count": 1
},
{
"first": "Adam", "last": "Doe", "count": 1
}
I've tried the below but it obviously only counts the unique "first" values and I'm not able to find a way to consider the second attribute "last" as well.我试过下面的方法,但它显然只计算唯一的“第一个”值,我无法找到一种方法来考虑第二个属性“最后”。
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)
You can count the tuples (first,last) in your counter:您可以在计数器中计算元组(第一个,最后一个):
Counter((i['first'], i['last']) for i in data)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.