源代码:使用字典
# Program to count the number of each vowels
# string of vowels
vowels = 'aeiou'
ip_str = 'Hello, have you tried our tutorial section yet?'
# make it suitable for caseless comparisions
ip_str = ip_str.casefold()
# make a dictionary with each vowel a key and value 0
count = {}.fromkeys(vowels,0)
# count the vowels
for char in ip_str:
if char in count:
count[char] += 1
print(count)
输出
{'a': 2, 'e': 5, 'i': 3, 'o': 5, 'u': 3}
这里,我们取了一个存储在 ip_str 中的字符串。使用方法 casefold()
,我们使其适合不区分大小写的比较。基本上,此方法返回字符串的小写版本。
我们使用字典方法 fromkeys()
构造一个新字典,其中每个元音作为其键,所有值都等于 0。这是计数的初始化。
接下来,我们使用 for 循环遍历输入字符串。
在每次迭代中,我们检查字符是否在字典键中(如果是元音则为 True
),如果为 true,则将值增加 1。
源代码:使用列表和字典推导式
# Using dictionary and list comprehension
ip_str = 'Hello, have you tried our tutorial section yet?'
# make it suitable for caseless comparisions
ip_str = ip_str.casefold()
# count the vowels
count = {x:sum([1 for char in ip_str if char == x]) for x in 'aeiou'}
print(count)
此程序的输出与上面相同。
这里,我们嵌套了一个列表推导式在一个字典推导式中,以一行代码计算元音数量。
字典推导式针对所有元音字符运行,字典推导式中的列表推导式检查字符串中的任何字符是否与该特定元音匹配。
最后,生成一个包含每个元音字符数量的 1 的列表。sum() 方法用于计算每个列表元素的总和。
然而,这个程序更慢,因为我们为每个元音遍历整个输入字符串。
另请阅读