Skip to main content
 首页 » 编程设计

python,代码的不同结果

2025年05月04日16bonelee

我的第一个函数哪里出错了?我有这个:

def fun(str):     
    for vowel in str: 
        if vowel in 'aeiouAEIOU': 
            return len(vowel) 

def fun(str): 
    return len([vowel for vowel in str if vowel in 'aeiouAEIOU']) 
 
print fun("halloo") 

这两个函数的结果是不同的。我必须返回字符串包含的元音字母数。

请您参考如下方法:

在您的第一个函数中,您会在找到元音时立即返回,并返回该元音的长度。结果总是 1(找到元音)或 None(没有找到元音)。

如果你想计算元音的数量,你必须使用一个新变量来跟踪该计数:

def fun(str): 
    count = 0 
    for vowel in str: 
        if vowel in 'aeiouAEIOU': 
            count += 1 
    return count 

第二个函数首先生成所有元音的列表,然后获取该列表的长度。你可以使用:

def fun(str): 
    return sum(1 for vowel in str if vowel in 'aeiouAEIOU') 

甚至不生成列表,只生成元音计数。