【问题标题】:Handling Errors/Exceptions in a Loop在循环中处理错误/异常
【发布时间】:2018-04-06 22:04:58
【问题描述】:

我有两个对应的列表:

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

【问题讨论】:

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


    【解决方案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
    

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

    【讨论】:

      【解决方案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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多