本文介绍了Python:计算字符串中列表项的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下列表

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

和另一个列表

words = ["happiness", "yellow"]

如何计算每个单词中的元音数量,即幸福= 3,黄色= 2?

how do I count the number of vowels in each word, i.e. happiness = 3, yellow=2?

推荐答案

使用列表理解:

>>> 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}

vowels转换为set将使其更有效.

Converting vowels to set will make it more effective.

这篇关于Python:计算字符串中列表项的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 05:26