此代码的目的是按字母顺序查找第一个出现的最长字符串并返回该子集。
我可以执行一次代码,但是当我尝试循环它时,我得到“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
。
关于python - “NoneType”对象不可迭代 - 带返回值的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30873224/