如果我有以下列表
vowels = ["a","e","i","o","u"]
和另一个清单
words = ["happiness", "yellow"]
如何计算每个单词中元音的数量,即happiness = 3,yellow = 2?
答案 0 :(得分:6)
使用列表理解:
>>> 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
会使其更有效。
答案 1 :(得分:0)
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
数据现在包含与单词列表相同的索引对应的元音数。干杯! :)