【问题标题】:How count the number of occurrences of all the values in a dictionary in python? TypeError: unhashable type: 'list'如何计算python字典中所有值的出现次数?类型错误:不可散列类型:“列表”
【发布时间】:2023-04-09 15:28:02
【问题描述】:

我想计算每个名字在字典中出现的次数(如下):

这是我的字典:

{'blue': ['Jules', 'Lucie'],
 'brown': ['Maxime'],
 'green': ['Maxime', 'Vincent', 'Lucie']}

这是我的代码:

from collections import Counter

Counter(dico.values())

我有这个错误:TypeError: unhashable type: 'list'

这是我想要的结果:

Jules   1
Lucie   2
Maxime  2
Vincent 1

【问题讨论】:

  • 你的预期输出是什么?

标签: python list dictionary collections counter


【解决方案1】:

也可以使用两个元组推导式来执行此操作:

from collections import Counter
your_dict = {'blue': ['Jules', 'Lucie'],
             'brown': ['Maxime'],
             'green': ['Maxime', 'Vincent', 'Lucie']}
Counter((inner_val for val in your_dict.values() for inner_val in val))

输出:

Counter({'Jules': 1, 'Lucie': 2, 'Maxime': 2, 'Vincent': 1})

【讨论】:

    【解决方案2】:

    为了计算列表中值的出现次数,需要对列表进行链接/展平:

    from itertools import chain
    from collections import Counter
    
    d = {'blue': ['Jules', 'Lucie'],
         'brown': ['Maxime'],
         'green': ['Maxime', 'Vincent', 'Lucie']}
    
    Counter(chain(*d.values()))
    

    chain 调用将列表转换为包含所有值的单个可迭代对象,结果是:

    Counter({'Lucie': 2, 'Maxime': 2, 'Jules': 1, 'Vincent': 1})

    【讨论】:

    • 你赢了我半分钟
    • 是的,这正是我想要做的。我说错了。感谢您的帮助。
    猜你喜欢
    • 2021-02-22
    • 2016-01-11
    • 1970-01-01
    • 2019-08-29
    • 2021-06-16
    • 2020-04-13
    • 2017-03-11
    • 1970-01-01
    • 2023-03-06
    相关资源
    最近更新 更多