【问题标题】:"histogram" function: input strings and output dictionary“直方图”功能:输入字符串和输出字典
【发布时间】:2014-11-24 18:23:28
【问题描述】:

我正在尝试创建一个histogram 函数,该函数接受字符串并计算字符串被使用并放入字典的次数。我还在学习 Python,所以任何提示都会有所帮助。

>>> histogram('The Goose that Laid the Golden Egg') 
{'l': 2, 'n': 1, 'o': 3, 'h': 3, 'i': 1,'d': 2,   'e': 5, 'g': 4, ' ': 6, 'a': 2, 't': 4, 's': 1} 

【问题讨论】:

    标签: python dictionary histogram


    【解决方案1】:

    这就是collections.Counter 的用途:

    >>> from collections import Counter
    >>> Counter('The Goose that Laid the Golden Egg')
    Counter({' ': 6, 'e': 4, 'h': 3, 'o': 3, 't': 3, 'a': 2, 'd': 2, 'G': 2, 'g': 2, 'i': 1, 'L': 1, 'l': 1, 's': 1, 'T': 1, 'E': 1, 'n': 1})
    

    【讨论】:

    • 不客气,This module implements specialized container datatypes providing alternatives to Python’s general purpose built-in containers, dict, list, set, and tuple.它是python数据结构中的必要模块!尝试学习它!
    【解决方案2】:

    我不会为你解决这个问题,但会给你一个提示:使用collections.Counter。将这一点与字符串可迭代的事实相结合,这让您非常接近解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多