如何跳过 python 中的记录

how to skip from a recored in python

我做了一个循环来计算单词列表中单词出现的次数。所以我使用以下代码:

for i in range(len(traindocs_clean)):
    for word in traindocs_clean[i][1][0]:
        if traindocs_clean[i][1] is None:
            continue
        wordDict[word]+=1

但我知道有些行的值为 null/NoneType/Blank,所以当我 运行 代码时,我将得到以下错误

     for word in traindocs_clean[i][1][0]:
TypeError: 'NoneType' object is not subscriptable

我尝试使用关键字 'continue' 和“pass”来忽略这些记录并跳转到下一条,但显然它不起作用。 我搜索了过去的评论和 posts 但我无法得到正确的答案所以如果你认为已经有一些 post 与此相同请分享 link 否则我很感激你的帮助我有一个解决方案。 谢谢

您可以使用 try-except 块处理异常:

for i in range(len(traindocs_clean)):
    try:
        for word in traindocs_clean[i][1][0]:
            wordDict[word] += 1
    except TypeError:
        pass

注意:最好不要使用pass和log,或者以适当的方式处理错误。

使用 try-except 的另一个优点是让您能够处理多个异常 and/or 在不同的情况下执行 运行 不同的命令。例如,如果你的代码也容易出现 IndexError 你可以这样做:

    try:
        for word in traindocs_clean[i][1][0]:
            wordDict[word] += 1
    except (TypeError, IndexError):
        pass

或者如果您想用 IndexError 以另一种方式治疗:

    try:
        for word in traindocs_clean[i][1][0]:
            wordDict[word] += 1
    except TypeError:
        pass
    except IndexError:
        # do something 
for word in traindocs_clean[i][1][0]:
    if traindocs_clean[i][1] is None:
        continue

if 条件检查 traindocs_clean[i][1] is Nonefor 循环是否已经尝试访问(并迭代)raindocs_clean[i][1][0]。如果 raindocs_clean[i][1]None 那么它会在 if 条件有机会验证 traindocs_clean[i][1] 不是 None 之前失败。

要解决此问题,您应该将 if 条件移动到 for 循环之上:

for i in range(len(traindocs_clean)):
    if traindocs_clean[i][1] is None:
        continue
    for word in traindocs_clean[i][1][0]:
        wordDict[word] += 1