【问题标题】:How to count elements in a list and return a dict? [duplicate]如何计算列表中的元素并返回字典? [复制]
【发布时间】:2016-02-27 16:23:50
【问题描述】:

假设我有一个列表

L = ['hello', 'hello', 'hi', 'hello', 'hello']

我想计算列表中有多少'hello''hi'。所以结果是'hello': 4'hi': 1

我将如何以字典形式实现此结果?我的教授还没有研究过这个,所以我不确定如何从列表转换为字典。

【问题讨论】:

  • 你听说过Counter吗?
  • 这可能不符合家庭作业的精神。
  • 你必须向我们展示解决这个问题的一些尝试,因为 SO 不是家庭作业完成服务。
  • 我不是要求代码答案。我只是想看看是否有任何内置函数(例如 Counter,如上面提到的 Avinash)。
  • 使用dict理解的一些冗余,但它可能是d = {itm:L.count(itm) for itm in L}

标签: python dictionary


【解决方案1】:

使用计数器:

>>> from collections import Counter
>>> def how_many(li): return Counter(li)
... 
>>> how_many(['hello', 'hello', 'hi', 'hello', 'hello'])
Counter({'hello': 4, 'hi': 1})

或者,你可以这样做:

>>> li=['hello', 'hello', 'hi', 'hello', 'hello']
>>> {e:li.count(e) for e in set(li)}
{'hi': 1, 'hello': 4}

或者,你可以这样做:

>>> di={}
>>> for e in li:
...    di[e]=di.get(e, 0)+1
... 
>>> di
{'hi': 1, 'hello': 4}

【讨论】:

    【解决方案2】:

    不使用外部模块,只使用count,尽管使用字典理解会有一些冗余:

    d = {itm:L.count(itm) for itm in set(L)}
    

    如果允许您使用外部模块并且不需要自己实现所有内容,则可以使用 Python 的 defaultdict,它通过 collections 模块提供:

    #!/usr/bin/env python3
    # coding: utf-8
    
    from collections import defaultdict
    
    word_list = ['hello', 'hello', 'hi', 'hello', 'hello']
    
    d = defaultdict(int)
    for word in word_list:
        d[word] += 1
    
    print(d.items())
    

    给你:

    dict_items([('hi', 1), ('hello', 4)])
    

    编辑: 如 cmets 中所述,您可以像这样使用Counter,这样会更容易:

    #!/usr/bin/env python3
    # coding: utf-8
    
    from collections import Counter
    
    word_list = ['hello', 'hello', 'hi', 'hello', 'hello']
    
    c = Counter(word_list)
    
    print(c)
    

    给你:

    Counter({'hello': 4, 'hi': 1})
    

    【讨论】:

    • 我不理解投反对票,这不是一个糟糕的答案,只是一个不同的答案
    • 您的第一个答案正是我想要的。谢谢!
    • -1: {itm:L.count(itm) for itm in L} 只是用更新的计数擦除 dict 键,直到重复项的最终唯一列表值。浪费和缓慢。您应该执行{itm:L.count(itm) for itm in set(L)},以便列表中的每个唯一条目仅执行一次计数步骤。
    • @thewolf:这不是我回答的一部分,而是由 David Zemens 补充的。由于您的评论,我更新了我的答案。感谢您的改进。
    猜你喜欢
    • 2021-04-05
    • 2022-01-10
    • 1970-01-01
    • 2021-12-03
    • 2021-08-11
    • 1970-01-01
    • 2021-07-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多