簡體   English   中英

Python List Comprehension - 從嵌套數據中提取

[英]Python List Comprehension - extracting from nested data

我是 Python 新手,試圖提取一些嵌套數據。

這是兩個產品的 JSON。 一個產品可以屬於零個或多個類別

 {  
   "Item":[  
      {   
         "ID":"170",
         "InventoryID":"170",
         "Categories":[  
            {  
               "Category":[  
                  {  
                    "CategoryID":"444",
                    "Priority":"0",
                    "CategoryName":"Paper Mache"
                  },
                  {  
                     "CategoryID":"479",
                     "Priority":"0",
                     "CategoryName":"Paper Mache"
                  },
                  {  
                     "CategoryID":"515",
                     "Priority":"0",
                     "CategoryName":"Paper Mache"
                  }
               ]
            }
         ],
         "Description":"Approximately 9cm wide x 4cm deep.",
         "SKU":"111931"
      },
      {  
         "ID":"174",
         "InventoryID":"174",
     "    Categories":[  
            {  
                "Category":{  
                  "CategoryID":"888",
                  "Priority":"0",
                  "CategoryName":"Plaster"
                }
            }
         ],
         "Description":"Plaster Mould - Australian Animals",
         "SKU":"110546"
      }
   ],
   "CurrentTime":"2016-08-22 11:52:27",
   "Ack":"Success"
}

我想確定產品屬於哪個類別。

我的提取代碼如下:-

        for x in products: 
            productsInCategory = []
            for y in x['Categories']:
                for z in y['Category']:
                    if z['CategoryID'] == categories[i]['CategoryID']:
                        productsInCategory.append(x)

這個問題是,在這種情況下,第二項只包含一個類別,而不是一系列類別,所以這一行

for z in y['Category']:

循環遍歷 Category 而不是 Category 數組的屬性,因此導致我的代碼失敗。

我該如何防范? 用列表理解語法可以更優雅地編寫它嗎?

在這種情況下,這是一個非常糟糕的文檔結構; 你不應該處理這個。 如果一個項目可以包含多個值,它應該始終是一個列表。

盡管如此,您仍然可以通過檢查它是否是列表來在代碼中處理它。

for x in products: 
    productsInCategory = []
    for y in x['Categories']:
        category = y['Category']
        if isinstance(category, dict):
            category = [category]
        for z in category:
            ...

(您可能需要考慮使用更具描述性的變量名稱; xyz對閱讀代碼的人不是很有幫助。)

我以前在 JSON 結構中經常遇到這個問題……經常到幾周前我為它寫了一個小庫……

嵌套密鑰檢索器 (nkr)

試試發電機,看看它是否能解決你的問題。 你應該能夠簡單:

for x in products: 
    if product_id_searching_for in list(nkr.find_nested_key_values(x, 'CategoryID')):
         productsInCategory.append(x)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM