在循环中处理错误/异常

2024-03-29 10:11:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个对应的列表:

  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对象的项。在


Tags: of项目对象函数脚本json列表index
2条回答

您可以创建一个列表理解并将其解压缩:

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)

不要试图修改正在迭代的列表;这会破坏迭代器。相反,构建并返回新列表。在

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

如果您坚持修改原始参数:

^{pr2}$

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

相关问题 更多 >