【问题标题】:Create a complicated form of dictionary with try and except使用 try 和 except 创建复杂形式的字典
【发布时间】:2020-07-09 03:00:43
【问题描述】:

在整个项目中我一直非常虔诚地使用列表推导,最后我遇到了一些元素没有所需索引范围的问题。

这是我的代码以便更好地理解:

result_box_lst = [{
            "coordinates": box['boundingPoly']['normalizedVertices'], 
            "product": [{
                "product_name"  : product["product"]["name"],
                "product_uri"   : product["product"]["img_uri"],
                "price"         : product["product"]["product_price"],
###################### problematic area #############################################
                "product_label1": product["product"]["productLabels"][1]["value"],
                "product_label2": product["product"]["productLabels"][2]["value"],
                "product_label3": product["product"]["productLabels"][3]["value"],
######################################################################################
                "score"         : product["score"]
                } for product in box['results'] if product["score"] >  0.25]
        } for box in grouped_results]

这里的问题是,有时product["product"]["productLables"] 在列表中没有多个元素,因此列表理解崩溃并出现IndexOutofRange 异常。所以我想用 try 和 except 来捕捉它,然后用谷歌搜索它,但是很可惜,列表推导式中不能有 try/except

因此,我开始使用 for 循环的基本方式进行编码,并且想知道如何使用 for 循环的基本形式创建相同结构的复杂字典/列表。到目前为止,我构建了这个:

result_box_lst = []
product = []
        for box in grouped_results:
            for product in box['results']:
                if product["score"] >  0.25:
                    try:

                    products.append({
                        "product_name": product["product"]["name"],
                        "product_uri"   : product["product"]["img_uri"],
                        "price"         : product["product"]["product_price"],
                        "product_label1": product["product"]["productLabels"][1]["value"],
                        "product_label2": product["product"]["productLabels"][2]["value"],
                        "product_label3": product["product"]["productLabels"][3]["value"],
                        "score"         : product["score"]
                    })

                    except:
                    pass

但是,我非常有信心,这永远不会实现我的愿望。有没有办法用这个 for 循环制作如此复杂的字典/列表?

【问题讨论】:

    标签: python list-comprehension


    【解决方案1】:

    这是一个非常复杂的理解,因此 for 循环可能最终变得更具可读性和可维护性。但是,如果您唯一的问题是有时您的列表索引超出范围,您可以使用 if / else 处理它:

    "product_label2": product["product"]["productLabels"][2]["value"] if len(product["product"]["productLabels"]) > 2 else "",
    "product_label3": product["product"]["productLabels"][3]["value"] if len(product["product"]["productLabels"]) > 3 else ""
    

    另外,你是否故意使用索引[1][2][3] 而不是[0][1][2]?只是检查...

    【讨论】:

      【解决方案2】:

      你可以试试这样的:

      for box in grouped_results:
          for product in box['results']:
              if product["score"] >  0.25:
                  data = {
                      "product_name": product["product"]["name"],
                      "product_uri"   : product["product"]["img_uri"],
                      "price"         : product["product"]["product_price"],
                      "score"         : product["score"]
                  }
                  for i in range(1,4):
                      if i < len(product["product"]["productLabels"]):
                          data['product_label{}'.format(i)] = product["product"]["productLabels"][i]["value"]
                      else:
                          data['product_label{}'.format(i)] = "Some default value"
                  products.append(data)
      

      但请注意,数组以 0 开头,因此您可能需要根据您的情况进行一些更改

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-02-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-20
        • 1970-01-01
        • 2018-08-10
        相关资源
        最近更新 更多