在没有 continue 语句的情况下忽略 Python2.7 中的 IndexError

Ignore an IndexError in Python2.7 without continue statement

我在 for 循环中有一个 try 和 except 语句。我正在查看存储在(可能过于复杂)列表中的数据,该列表本身存储在 defaultdict 中。我期待 IndexErrors,但当它们发生时我根本不需要比较任何数据,所以我想忽略该错误。这是我当前的代码:

for key, list_item in defdict.iteritems():
    if len(list_item) == 2:
        if len(list_item[0][1]) > 1 or len(list_item[1][1]) > 1:
            compare00,compare01=[],[]
            if another_list.__contains__(list_item[0][0]):
                try:
                    for item in defdict.iteritems():
                        if item[1][0][0] == list_item[0][0]:
                            compare00.append(compare_function(item))
                except IndexError:
                    continue
            if another_list.__contains__(list_item[1][0]):
                try:
                    for item in defdict.iteritems():
                        if item[1][1][0] == list_item[1][0]:
                            compare10.append(compare_function(item))
                except IndexError:
                    continue
        print compare00,compare10
        #etc

我后来意识到 continue 的说法是不正确的。我的 if 语句不需要相互排斥,因此,进入循环的下一次迭代 (continue) 或离开循环 (break) 都不合适。没有 continue 的空白 except IndexError: 是不正确的语法。我应该如何忽略错误?

使用pass语句代替continue语句

如果您想继续循环,请使用 pass 而不是 continue
如果你想停止循环然后使用 break 而不是 continue.