【问题标题】:How to add words and values into a dictionary? [duplicate]如何将单词和值添加到字典中? [复制]
【发布时间】:2018-03-16 03:32:48
【问题描述】:

我正在编写一个代码,它接受用户输入并计算一个单词出现的次数。我需要使用字典,因为这是学校作业。

如果我让用户输入如下内容:

"a turtle on a fence had help"

那么输出将是:

{'a': 2, 'turtle': 1, 'on': 1, 'fence': 1, 'had': 1, 'help': 1}

我知道我需要将单词添加到字典中,如果它首先不在字典中,则将值设为 1。我也知道如果它在字典中,我需要将值增加 1每次出现后。我只是不完全确定如何执行该过程。

【问题讨论】:

  • 你有没有尝试过?
  • 我可能会拆分字符串,然后遍历它并检查单词/字母是否已经在字典中。如果是 +=1,如果不是,则创建一个新的 dict 项。
  • 这可能对你有帮助,work to dictionary

标签: python


【解决方案1】:

你可以看看Counter

from collections import Counter

c  = "a turtle on a fence had help"

dict(Counter(c.split()))

输出:

{'a': 2, 'fence': 1, 'had': 1, 'help': 1, 'on': 1, 'turtle': 1}

您需要将其拆分为“”,因为在 python 中,字符串的行为类似于不可变列表。这意味着您可以像列表(c[0] -> "a")一样访问数据,但执行c[0] = "p" 会引发TypeError

【讨论】:

    【解决方案2】:
    >>> sentence = 'a turtle on a fence had help'
    >>> output = {}
    >>> for word in sentence.split():
    ...     if word not in output.keys():
    ...             output[word] = 0
    ...     output[word] += 1
    ...
    >>> print(output)
    {'a': 2, 'turtle': 1, 'help': 1, 'fence': 1, 'on': 1, 'had': 1}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-17
      • 1970-01-01
      相关资源
      最近更新 更多