for 循环减少到列表理解或使用 lambda 函数

for loops reduction to list comprehension or use of lambda function

categories = [
  {
    "CategoryUId": "f34cc7a8-ac38-4f1f-a637-08bd034d74f3",
    "SubCategory": [
      {
        "SubCategoryUId": "9b37dbf3-4b4d-4bbb-8bc4-2ce036b69042"
      },
      {
        "SubCategoryUId": "d4131c98-9823-4354-b587-c736cd77df4d"
      }
    ]
  },
  {
    "CategoryUId": "460366f6-c8ef-4e4e-80a7-4ace9c59122c",
    "SubCategory": [
      {
        "SubCategoryUId": "ed6dbfb9-bc1a-4161-b040-f9aba55c995a"
      },
      {
        "SubCategoryUId": "06246a88-fe8a-42fa-aba6-3393af463397"
      },
      {
        "SubCategoryUId": "2f37fd26-fae5-4dc4-9f10-4e87a2f5ae68"
      }
    ]
  }
]

一个基本示例,其中类别是字典列表。

for item in categories:
    categoryUId = item['CategoryUId']
    for value in item['SubCategory']:
        subcategory = value['SubCategoryUId']
        subcategoryList.append(subcategory)
    dict = {categoryUId : subcategoryList}

我正在做一些随机的 python 练习,是否可以对上述代码片段使用 lambda 函数或列表理解。

请帮我一个方法。

看来这就是你所期望的结果:

out = {d['CategoryUId']: [v['SubCategoryUId'] for v in d['SubCategory']] for d in categories}

上面的代码在 map 中有一个 lambda(虽然非常难看;不推荐):

out = dict(map(lambda d: (d['CategoryUId'], [*map(lambda v:v['SubCategoryUId'], d['SubCategory'])]), categories))

输出:

{'f34cc7a8-ac38-4f1f-a637-08bd034d74f3': ['9b37dbf3-4b4d-4bbb-8bc4-2ce036b69042',
  'd4131c98-9823-4354-b587-c736cd77df4d'],
 '460366f6-c8ef-4e4e-80a7-4ace9c59122c': ['ed6dbfb9-bc1a-4161-b040-f9aba55c995a',
  '06246a88-fe8a-42fa-aba6-3393af463397',
  '2f37fd26-fae5-4dc4-9f10-4e87a2f5ae68']}