对于循环或while循环?

时间:2015-07-15 22:02:39

标签: python python-3.x

哪个函数定义在Python中更有效,即使它们执行相同的任务?我应该何时使用for循环,何时应该使用while循环?

def count_to_first_vowel(s):
    '''  (str) -> str
    Return the substring of s up to but not including the first vowel in s. If no vowel
    is present, return s.
    >>> count_to_first_vowel('hello')
    'h'
    >>> count_to_first_vowel('cherry')
    'ch'
    >>> count_to_first_vowel('xyz')
    xyz
    '''
    substring = ''
    for char in s:
        if char in 'aeiouAEIOU':
            return substring
        substring = substring + char
    return substring

def count_to_first_vowel(s):
    '''  (str) -> str
    Return the substring of s up to but not     including the first vowel in s. If no vowel
    is present, return s.
    >>> count_to_first_vowel('hello')
    'h'
    >>> count_to_first_vowel('cherry')
    'ch'
    >>> count_to_first_vowel('xyz')
    xyz
    '''
    substring = ''
    i = 0
    while i < len(s) and not s[i] in 'aeiouAEIOU':
        substring = substring + s
        i = i + 1
    return substring

1 个答案:

答案 0 :(得分:0)

for循环计算一次长度,并知道这一点。 while循环必须评估每个循环len(s)。每次评估while语句时,访问字符串的单个索引可能会有更多的开销。

如果while循环每次重新计算len()之类的内容,我认为使用for会更有效率。他们两个都必须测试每个循环至少一个条件。

重写while循环以使用类似len = len(s)的保存变量可能会删除该额外位并使它们非常接近。当您考虑到for循环正在执行第二个内部循环时,情况会更好。

相关问题