Python 3.x 为什么我的代码返回TypeError:';非类型';对象不可编辑?

Python 3.x 为什么我的代码返回TypeError:';非类型';对象不可编辑?,python-3.x,string,dictionary,nonetype,Python 3.x,String,Dictionary,Nonetype,我试图定义一个函数,该函数检查字符串是否包含字典中的单词,并返回true以及匹配的单词。下面是一段代码,当一个单词与字典中的字符串匹配时,一切正常 def trigcheck(strings,a): try: str = strings.split() m='' a_match = [True for match in a if match in str] a=[m for m in a if m in str]

我试图定义一个函数,该函数检查字符串是否包含字典中的单词,并返回true以及匹配的单词。下面是一段代码,当一个单词与字典中的字符串匹配时,一切正常

def trigcheck(strings,a):
    try:
        str = strings.split()
        m=''
        a_match = [True for match in a if match in str]
        a=[m for m in a if m in str]
        if True in a_match:
            return True,a[0]

    except:
        return False,""

bool1,w=trigcheck("kjfdsnfbdskjhfbskdabs",['hello','do'])
print(bool1)
print(w)
我本来希望with字符串不匹配时应该返回False和“”。但它抛出了一个错误,即:

bool1,w=trigcheck("kjfd s n f dobdskjhfbskdabs",['hello','do'])
TypeError: 'NoneType' object is not iterable

如果您没有引发异常,并且
True
不在
a_match
中,则根本不显式
return
,从而隐式返回
None
。将
None
解包到
bool1
w
会引发异常

如果
如果
检查失败,则通过使异常返回无条件来修复代码:

def trigcheck(strings,a):
    try:
        str = strings.split()
        m=''
        a_match = [True for match in a if match in str]
        a=[m for m in a if m in str]
        if True in a_match:
            return True,a[0]

    except Exception:  # Don't use bare except unless you like ignoring Ctrl-C and the like
        pass
    # Failure return is outside except block, so fallthrough reaches
    # it whether due to an exception or because the if check failed
    return False,""
附加说明:您对现有
匹配的测试相对低效;它不能短路,需要一个临时的
列表
。用以下代码替换函数体,在没有匹配项时,该代码依赖于异常处理返回:

def trigcheck(strings,a):
    try:
        strings = strings.split()  # Don't nameshadow builtins, reuse strings instead of shadowing str
        return True, next(m for m in a if m in strings)
    except StopIteration:
        return False, ""

将三次扫描和两次临时
列表
s减少为一次扫描和无临时列表,并通过仅捕获指示找不到匹配项的一个来避免压制随机异常(例如
类型错误
,因为有人将非字符串或非iterable作为参数传递),您的函数返回NONE可能也不应该使用
str
作为变量名,因为这是内置的。如果这是问题所在,那么在成功匹配时它甚至不应该返回true。可能的修复方法是执行
pass
in except并在结尾返回
False“
?@deveshkumarsing:是的,你发表评论时,我正在写这篇文章。:-)