python - 如何在python中为字典使用计数器
问题描述
我正在尝试计算员工头衔
我已经尝试了很多,但我认为我没有正确地将它们应用到场景中。
employees = [
{
"email": "jonathan2532.calderon@gmail.com",
"employee_id": 101,
"firstname": "Jonathan",
"lastname": "Calderon",
"title": "Mr",
"work_phone": "(02) 3691 5845"
}]
EDIT:
from collections import Counter
class Employee:
def __init__(self, title,):
self.title = title
title_count = Counter()
for employee in [Employee("title") for data in employees]:
title_count[employee.title,] += 1
print(title_count)
Counter({('title',): 4})
我似乎无法获得那里的具体名称。
解决方案
这里有几件事,欢迎堆栈溢出。请阅读如何提出一个好问题。接下来,python 试图帮助你解决它给你的错误。
尝试将错误的一部分复制并粘贴到谷歌中。然后,访问有关您尝试使用的数据类型的文档。我认为你的问题已经过编辑,但是是的——它仍然会有所帮助。
最后,我们需要看一个最小的、完整的、可验证的例子。所以,代码,我们需要看看你试图用什么样的代码来解决你的问题。
考虑数据的结构会有所帮助:
from collections import Counter
class Employee:
def __init__(self, title, employee_id):
# all other fields omitted
self.title = title
self.employee_id = employee_id
这是您的问题的一些最小数据(可以说您可以使用更少的数据)。
employees = [
{
"title": "Mr",
"employee_id": 1
},
{
"title": "Mr",
"employee_id": 2
},
{
"title": "Mrs",
"employee_id": 3
},
{
"title": "Ms",
"employee_id": 4
}
]
定义其他必要的数据结构。
title_count = Counter()
# Just to demo results.
for employee in [Employee(**data) for data in employees]:
print(f"title: {employee.title} id: {employee.employee_id}")
我会把**data
符号留给谷歌。但是现在你有一些结构良好的数据,并且可以相应地处理它。
# Now we have some Employee objects with named fields that are
# easier to work with.
for employee in [Employee(**data) for data in employees]:
title_count[employee.title] += 1
print(title_count) # Counter({'Mr': 2, 'Mrs': 1, 'Ms': 1})
推荐阅读
- python - 多线程将请求放入python
- typescript - 打字稿枚举静态检查
- python - 使用 PointField 测试 django geoodel 会导致 TypeError
- firebase - Firebase 实时数据库数据即将到来,即使它已被删除
- sql - 如何同时查询多个范围内的数据及其计数
- api - 万事达卡 3D 安全 | AUTHENTICATION_PENDING | 拒绝状态
- python - pythin 脚本中的类型错误
- docker - Docker Volume 引用格式无效
- c# - 使用 Cake 运行 DotCover dotnet 测试
- node.js - 使用 axios 在 Nuxt.js 中上传图片