【问题标题】:Given a list, can can I use dictionary comprehension to represent list items as keys and how many times they show up in the list as values? [duplicate]给定一个列表,我可以使用字典理解将列表项表示为键以及它们在列表中显示为值的次数吗? [复制]
【发布时间】:2018-03-27 05:57:43
【问题描述】:

基本上我正在编写一个函数,它接收一个列表作为输入并返回一个字典,该字典计算列表中数据重复的次数。

#Example:
count_occurrences(["a", "b", "c", "a", "a," "b"])

#output: 
{"a" : 3, "b" : 2, "c": 1}

到目前为止,我的解决方案是:

def count_occurrences(a_list):
    count_list = {}
    for i in a_list:
        if i not in count_list:
            count_list[i] = 1
        else: 
            count_list[i] += 1 
    return count_list 

但我想知道是否有办法使用字典理解来缩短/优化这个脚本。

【问题讨论】:

标签: python python-3.x list dictionary-comprehension


【解决方案1】:

有一个专门为此而制作的内置类。它被称为计数器,它已经实现了一个字典,你不需要转换它。

from collections import Counter

print(Counter(["a", "b", "c", "a", "a", "b"]))

#Output
Counter({'a': 3, 'b': 2, 'c': 1})

【讨论】:

    猜你喜欢
    • 2019-06-15
    • 2016-03-31
    • 1970-01-01
    • 1970-01-01
    • 2016-02-18
    • 1970-01-01
    • 2023-03-18
    • 2023-01-27
    • 2012-06-20
    相关资源
    最近更新 更多