有没有更有效的方法来计算一个字符串中有多少元音?

2024-09-30 06:30:35 发布

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

def processStrings(userPhrase):
    """ This function will accept the phrase as string and will count every 
        instance of vowel then return a dictionary with key:values of each 
        vowel and amount of occurrences in string.
    """

    vowelCount = {i:userPhrase.count(i) for i in 'AEIOU'}

    return (vowelCount)

我是新的堆栈溢出和编程。我写这个函数是作为课堂小程序的一部分,现在很想知道什么是最有效的解决方案。我们被告知在开发一个有效的解决方案时要对适用的概念有很强的理解,据我所知这已经非常接近了,因为它使用了一个字典,count()应该是好的。我想知道我是否遗漏了这样的东西,它必须在整个短语上迭代5次才能得到值,但我不知道是否有更好的解决方案,这意味着更少的处理时间或内存使用,比如说,如果我对一个更大的字符串使用函数,搜索的不仅仅是元音或其他东西。你知道吗


Tags: andof函数instringreturndefcount
1条回答
网友
1楼 · 发布于 2024-09-30 06:30:35

使用Counter,然后提取元音的值并复述它们可能会更有效:

from collections import Counter

def count_vowels(phrase):
    """ accepts a string and counts the number of each vowels.
    returns a dictionary key  > values 
            of each vowel and their number of occurrences.
    """
    vowels = "aeiou"
    frequencies = Counter(phrase.lower())
    return {vowel: frequencies[vowel] for vowel in vowels}    

作为一个班轮:

(正如@stevenRumbalski在评论中所建议的)

from collections import Counter

def count_vowels(phrase):
    """ accepts a string and counts the number of each vowels.
    returns a dictionary key  > values 
            of each vowel and their number of occurrences.
    """
    vowels = "aeiou"
    return Counter(c for c in phrase.lower() if c in vowels)

相关问题 更多 >

    热门问题