哪个函数定义在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
答案 0 :(得分:0)
for
循环计算一次长度,并知道这一点。 while
循环必须评估每个循环len(s)
。每次评估while
语句时,访问字符串的单个索引可能会有更多的开销。
如果while
循环每次重新计算len()
之类的内容,我认为使用for
会更有效率。他们两个都必须测试每个循环至少一个条件。
重写while
循环以使用类似len = len(s)
的保存变量可能会删除该额外位并使它们非常接近。当您考虑到for
循环正在执行第二个内部循环时,情况会更好。