【问题标题】:Python: Count number of occurrences of list items in a stringPython:计算字符串中列表项的出现次数
【发布时间】:2014-08-22 20:31:56
【问题描述】:

如果我有以下列表

vowels = ["a","e","i","o","u"]

还有另一个列表

words = ["happiness", "yellow"]

如何计算每个单词中元音的个数,即happy = 3, yellow=2?

【问题讨论】:

  • 将问题分解为更简单的问题...如何计算字符串中 ONE 字母的出现次数?一旦你有了它,你就可以浏览字母列表,并添加这个函数的结果。
  • 这个问题似乎离题了,因为这不是一个代码编写服务,而且这里已经有几十个关于使用 Python 计算元音的问题。

标签: python list python-2.7


【解决方案1】:

使用列表推导:

>>> vowels = ["a","e","i","o","u"]
>>> words = ["happiness", "yellow"]
>>> [sum(c in vowels for c in word) for word in words]
[3, 2]

如果您想在单词和出现之间进行映射,请使用字典理解:

>>> {word: sum(c in vowels for c in word) for word in words}
{'happiness': 3, 'yellow': 2}

vowels 转换为set 会更有效。

【讨论】:

    【解决方案2】:
    data = [0]*len(words)                # Initializing the data list
    for index, word in enumerate(words): # Iterating through the list of words
     for letter in list(word):
      if letter in vowels:               #checking if the letter is in vowels
       data[index] = data[index]+1
    print data
    

    data 现在包含与单词列表相同的索引对应的元音数量。干杯! :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-10
      • 1970-01-01
      相关资源
      最近更新 更多