【问题标题】:why my code returns TypeError: 'NoneType' object is not iterable? [duplicate]为什么我的代码返回 TypeError: 'NoneType' object is not iterable? [复制]
【发布时间】:2019-06-20 19:45:41
【问题描述】:

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

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)

我期待与不匹配的字符串应该返回 False 和 ' ' 。但它会抛出错误:

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

【问题讨论】:

  • 如果没有异常且没有匹配,你的函数返回 None
  • 可能你也不应该使用str作为变量名,因为这是一个内置的。
  • 如果这是问题所在,那么它甚至不应该在成功匹配时返回 true

标签: python-3.x string dictionary nonetype


【解决方案1】:

如果您不引发异常,并且True 不在a_match 中,则您根本没有显式地return,导致您隐式地返回None。将None 解包为bool1w 会引发异常。

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

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,""

附加说明:您对现有match 的测试效率相对较低;它不能短路,需要一个临时的list。用以下代码替换函数的主体,该代码依赖于在没有匹配项时返回的异常处理:

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, ""

将三个扫描和两个临时的lists 减少到一个扫描和没有临时列表,并避免沉默随机异常(例如,TypeError,因为有人传递了一个非字符串或不可迭代作为参数)只捕获表示找不到匹配项的那个。

【讨论】:

  • 一个可能的解决方法是在 except 中执行 pass 并在最后返回 False, ""
  • @DeveshKumarSingh:是的,当你发表评论时,我正在写这个。 :-)
猜你喜欢
  • 2020-06-17
  • 2017-08-01
  • 1970-01-01
  • 2014-02-17
  • 1970-01-01
  • 2021-11-03
  • 1970-01-01
  • 2020-06-20
  • 2020-05-07
相关资源
最近更新 更多