Skip to main content
 首页 » 编程设计

python之'NoneType' 对象不可迭代之带返回值的循环

2024年10月24日12lvdongjie

此代码的目的是按字母顺序找到最先出现的最长字符串并返回该子集。

我可以执行一次代码,但是当我尝试循环它时,我得到“NoneType”对象不可迭代(指向最后一行)。我确定我返回的和输入的都不是NoneType,所以我觉得我缺少一个基础。

这是我在类里面的第一个项目,因此代码不需要是“最佳”或最有效的方式 - 此时只是学习基础知识。

s = 'efghiabcdefg' 
best = '' 
comp = '' 
temp = '' 
 
def prog(comp, temp, best, s): 
    for char in s: 
        if comp <= char: #Begins COMParison of first CHARacter to <null> 
            comp = char  #If the following character is larger (alphabetical), stores that as the next value to compare to. 
            temp = temp + comp  #Creates a TEMPorary string of characters in alpha order. 
            if len(temp) > len(best):  #Accepts first string as longest string, then compares subsequent strings to the "best" length string, replacing if longer. 
                best = temp 
            if len(best) == len(s):  #This is the code that was added... 
                return(s, best)  #...to fix the problem.   
        else: 
            s = s.lstrip(temp)  #Removes those characters considered in this pass 
            return (str(s), str(best)) #Provides new input for subsequent passes 
 
while len(s) != 0: 
    (s, best) = prog(comp, temp, best, s) 

请您参考如下方法:

prog 正在返回 None。您得到的错误是当您尝试将结果解压缩到元组 (s, best)

您需要修复您的逻辑,以便保证 prog 不会返回 None。如果您的代码从不执行循环中的 else 子句,它将返回 None。