在循环中处理 Errors/Exceptions

Handling Errors/Exceptions in a Loop

我有两个对应的列表:

  1. 一个是项目列表
  2. 另一个是这些项目的标签列表

我想编写一个函数来检查第一个列表中的每个项目是否是一个 JSON 对象。如果是,则应保留在列表中,如果不是,则应将其及其相应标签删除。

我编写了以下脚本来执行此操作:

import json 
def check_json (list_of_items, list_of_labels):
    for item in list_of items:
        try:
            json.loads(item)
            break
        except ValueError:
            index_item = list_of_items.index(item)
            list_of_labels.remove(index_item)
            list_of_items.remove(index_item)

但是,它不会删除不是 JSON 对象的项目。

不要尝试修改您正在迭代的列表;它打破了迭代器。相反,构建 return 新列表。

import json 
def check_json (list_of_items, list_of_labels):
    new_items = []
    new_labels = []
    for item, label in zip(list_of items, list_of_labels):
        try:
            json.loads(item)
        except ValueError:
            continue
        new_items.append(item)
        new_labels.append(label)
    return new_items, new_labels

如果您坚持修改原参数:

def check_json (list_of_items, list_of_labels):
    new_items = []
    new_labels = []
    for item, label in zip(list_of items, list_of_labels):
        try:
            json.loads(item)
        except ValueError:
            continue
        new_items.append(item)
        new_labels.append(label)
    list_of_items[:] = new_items
    list_of_labels[:] = new_labels

但请注意,这并没有真正提高效率;它只是提供了一个不同的界面。

您可以创建一个列表理解并解压它:

def is_json(item):
    try:
        json.loads(item)
        return True
    except ValueError:
        return False


temp = [(item, label) for item, label in zip(items, labels) if is_json(item)]
items, labels = zip(*temp)