python - “NoneType”对象不可迭代 - 带返回值的循环

标签 python python-2.7

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

我可以执行一次代码,但是当我尝试循环它时,我得到“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/

相关文章:

python - 我的Python有什么问题?

python - 使用字符串调用 Python 实例的私有(private)属性

python - 用于排序循环的 odoo 电子邮件模板

python - 如何使用 Python 安排不受系统时间变化影响的周期性任务

python - 如何在 OpenCV Python 中检测红色?

python - 检查 shell 命令是否已成功执行的最佳方法

python - 使用带有口音和不同字符的 Beautiful Soup

python - 访问变量概念 : Ruby Vs Python

python - 来自 statsmodels 的自定义估算器 WLS 的 sklearn check_estimator 错误

python - python中的对象跟踪