python-计数JSON中值组合的发生

发布于 2025-01-26 06:01:25 字数 852 浏览 1 评论 0原文

我正在使用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

乜一 2025-02-02 06:01:25

您可以在计数器中计算元组(首先,最后):

Counter((i['first'], i['last']) for i in data)

You can count the tuples (first,last) in your counter:

Counter((i['first'], i['last']) for i in data)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文