gpt4 book ai didi

python - 如何对 list.count() 的结果求和

转载 作者:太空宇宙 更新时间:2023-11-04 08:25:32 25 4
gpt4 key购买 nike

我正在尝试总结字符串中元音的数量。如何计算计数结果的总和?

def count_vowels(string):
vowel = 'aeiou'
for i in list(vowel):
if i in list(string):
print(string.count(i))

count_vowels('abcod') # 2
count_vowels('coliioor') # 5
count_vowels('colour') #3

当前输出:

1 first word
1 first word
2 second word
3 second word
2 third word
1 third word

最佳答案

您可以使用sum() 函数:

def count_vowels(s):
return sum(ch in 'aeiou' for ch in s)

print(count_vowels('abcod')) # 2
print(count_vowels('coliioor')) # 5
print(count_vowels('colour')) #3

打印:

2
5
3

关于python - 如何对 list.count() 的结果求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57632347/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com