【问题标题】:How to use counter in python for dictionaries如何在python中为字典使用计数器
【发布时间】:2019-04-02 00:08:33
【问题描述】:

我正在尝试计算员工头衔

我尝试了很多,但我认为我没有正确地将它们应用到场景中。

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})

我似乎无法获得那里的具体名称。

【问题讨论】:

  • 您可以使用employees 发布您尝试运行的代码吗?
  • 首先:使用print(title) 查看变量中的内容。使用print() 可能是测试/调试代码的原始但有用的方法。

标签: python python-3.x


【解决方案1】:

在您的示例中,for title in employees 实际上在每次迭代中都会产生一个 dict 对象,因为 employees 是一个 dict 对象列表。虽然 Counter 接受 dict 映射作为输入,但它并不是您要寻找的。 cnt['title'] 只是将每次迭代的计数增加 1,有效地计算员工列表中 dict 对象的数量。

要按标题计数,您必须先解压缩列表中的每个 dict 对象。

from collections import Counter

titles = [e['title'] for e in employees]
>>>Counter(titles)
Counter({'Mr': 2, 'Mrs': 1, 'Ms': 1})

【讨论】:

    【解决方案2】:

    这里有几件事,欢迎堆栈溢出。请阅读how to ask a good question。接下来,python 试图帮助你解决它给你的错误。

    尝试将错误的一部分复制并粘贴到 Google 中。然后,访问您尝试使用的 data type 上的文档。我认为您的问题已经过编辑,但是是的——它仍然会有所帮助。

    最后,我们需要看到minimal, complete, and verifiable example。所以,代码,我们需要看看你试图用什么样的代码来解决你的问题。

    考虑数据的结构会有所帮助:

    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})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-04
      • 1970-01-01
      • 2020-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多