简体   繁体   English

Python:计算字符串中列表项的出现次数

[英]Python: Count number of occurrences of list items in a string

If I have the following list 如果我有以下列表

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

and another list 和另一个清单

words = ["happiness", "yellow"]

how do I count the number of vowels in each word, ie happiness = 3, yellow=2? 我如何计算每个单词中的元音数量,即幸福= 3,黄色= 2?

Using list comprehension: 使用列表理解:

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

If you want mapping between the words and occurences, use dictionary comprehension: 如果要在单词和出现之间进行映射,请使用字典理解:

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

Converting vowels to set will make it more effective. vowels转换为set将使其更有效。

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 now contains number of vowels corresponding to the same index as the words list. 数据现在包含与单词列表相同的索引对应的元音数。 Cheers! 干杯! :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM