python-计数JSON中值组合的发生
我正在使用python尝试解析json
文件。类似于此问题,我想计算出事件的数量文件中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)
I'm using python to try and parse a JSON
file. Similar to this question, I want to count the number of occurrences for each combination of 2 values in the file:
Example 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):
{
"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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在计数器中计算元组(首先,最后):
You can count the tuples (first,last) in your counter: