处理循环中的错误/异常

时间:2017-10-25 17:40:22

标签: python json python-2.7 error-handling exception-handling

我有两个相应的列表:

  1. 一个是项目列表
  2. 另一个是这些项目的标签列表
  3. 我想编写一个函数来检查第一个列表中的每个项目是否是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对象的项目。

2 个答案:

答案 0 :(得分:1)

不要试图修改你正在迭代的列表;它破坏了迭代器。而是构建并返回新列表。

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

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

答案 1 :(得分:0)

您可以创建列表解析并解压缩它:

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)