Dav*_*vid 1 python optimization control-flow
有没有办法在1个elif块的(false)评估和Python 3.x中的下一个评估之间执行语句?我想通过仅运行函数"word_in_special_list"来优化我的程序,如果if块的前2个语句评估为false.理想情况下,程序看起来像这样:
for word in lis:
#Finds word in list
if word_in_first_list(word):
score += 1
elif word_in_second_list(word):
score -= 1
#Since the first 2 evaluations return false, the following statement is now run
a, b = word_in_special_list(word)
#This returns a Boolean value, and an associated score if it's in the special list
#It is executed only if the word isn't in the other 2 lists,
#and executed before the next elif
elif a:
score += b #Add b to the running score
else:
...other things...
#end if
#end for
Run Code Online (Sandbox Code Playgroud)
当然,在elif评估中放置元组会返回错误.我也无法重构我的if语句,因为该单词更可能位于第一个或第二个列表中,因此这种结构可以节省时间.那么有没有办法在2个elif评估之间运行代码块?
你必须制作一个else案例,然后在其中嵌套
for word in lis:
if word_in_first_list(word):
score += 1
elif word_in_second_list(word):
score -= 1
else:
a, b = word_in_special_list(word)
if a:
score += b #Add b to the running score
else:
...other things...
Run Code Online (Sandbox Code Playgroud)