如何求结果的和列表.计数()

2024-05-07 23:49:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图总结一个字符串中元音的数量。如何计算计数结果的总和?你知道吗

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

Tags: 字符串in数量stringcountlistwordfirst
3条回答

您可以使用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

首先,您没有从函数返回任何内容,而且,您的函数应该使用一个变量来存储和,并在循环执行时不断增加它(而且您不需要将字符串转换为列表来对其进行迭代,字符串也是可iterable的):

def count_vowels(string):
    vowel = 'aeiou'
    result = 0
    for i in vowel:
        if i in string:
            result += string.count(i)
    return result

但是,更好的方法是反转循环:

def count_vowels(string):
    vowel = 'aeiou'
    result = 0
    for i in string:
        if i in vowel:
            result += 1
    return result

我认为这将有助于您(我已经注释了代码中没有的新行):

def count_vowels(string):
    sum_of_vowels = 0 # new line
    vowel = 'aeiou'
    for i in list(vowel):
        if i in list(string):
            sum_of_vowels += string.count(i) # new line
    return sum_of_vowels 


print(count_vowels('abcod'))
print(count_vowels('coliioor'))
print(count_vowels('colour'))

输出:

2
5
3

更好的方法:

像这样做this question

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

相关问题 更多 >