原文: https://www.programiz.com/python-programming/examples/count-vowel
在此程序中,您将学习使用字典和列表推导式来计算字符串中每个元音的数量。
要理解此示例,您应该了解以下 Python 编程主题:
源代码:使用字典
# Program to count the number of each vowels# string of vowelsvowels = 'aeiou'ip_str = 'Hello, have you tried our tutorial section yet?'# make it suitable for caseless comparisionsip_str = ip_str.casefold()# make a dictionary with each vowel a key and value 0count = {}.fromkeys(vowels,0)# count the vowelsfor char in ip_str:if char in count:count[char] += 1print(count)
输出
{'o': 5, 'i': 3, 'a': 2, 'e': 5, 'u': 3}
在这里,我们采用了存储在ip_str中的字符串。 使用方法casefold(),我们使其适合无条件比较。 基本上,此方法返回字符串的小写版本。
我们使用字典方法fromkeys()来构造一个新字典,其中每个元音作为其键且所有值等于 0。这是计数的初始化。
接下来,我们使用循环遍历输入字符串。
在每次迭代中,我们检查字符是否在字典键中(如果为元音则为True),如果为true,则将值增加 1。
源代码:使用列表和字典推导式
# Using dictionary and list comprehensionip_str = 'Hello, have you tried our tutorial section yet?'# make it suitable for caseless comparisionsip_str = ip_str.casefold()# count the vowelscount = {x:sum([1 for char in ip_str if char == x]) for x in 'aeiou'}print(count)
该程序的输出与上述相同。
在这里,我们将列表推导式嵌套在字典推导式内,以在单行中对元音进行计数。
但是,由于我们迭代每个元音的整个输入字符串,因此该程序的速度较慢。
