gpt4 book ai didi

python - 在 2 个 elif block 之间执行语句

转载 作者:太空宇宙 更新时间:2023-11-04 07:07:45 24 4
gpt4 key购买 nike

有什么方法可以在 1 个 elif block 的(错误)评估和 Python 3.x 中的下一个评估之间执行语句?如果 if block 的前 2 个语句评估为 false,我希望通过仅运行函数“word_in_special_list”来优化我的程序。理想情况下,程序看起来像这样:

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

当然,将元组放入 elif 求值会返回错误。我也无法重组我的 if 语句,因为该词更有可能出现在第一个或第二个列表中,因此这种结构可以节省时间。那么有什么方法可以在两次 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...

关于python - 在 2 个 elif block 之间执行语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32161730/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com