Skip to main content
 首页 » 编程设计

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

2025年05月04日10birdshome

有什么方法可以在 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...