首页 > 解决方案 > 从字典中获取所有具有列表值的组合(来自嵌套字典列表的笛卡尔积)

问题描述

我使用django-oscar并且我需要从一个父产品自动创建产品变体,该产品具有多种颜色、尺寸和纺织品选项。

我有以下 ProductAttributeValues 行,用于填充自动创建的变体。

# Basically, a list of dictionaries with 3 keys: 'value', 'attribute', 'product_class'
[
  OrderedDict([('value', <QuerySet [<AttributeOption: Black>, <AttributeOption: White>]>, <AttributeOption: Red>]>), ('attribute', <ProductAttribute: dress Color>), ('product_class', 'dress')]), 
  OrderedDict([('value', <QuerySet [<AttributeOption: M>, <AttributeOption: S>]>), ('attribute', <ProductAttribute: dress Size>), ('product_class', 'dress')]),
  OrderedDict([('value', <QuerySet [<AttributeOption: Cotton>, <AttributeOption: Wool>, <AttributeOption: Silk>, <AttributeOption: Nylon>]>), ('attribute', <ProductAttribute: dress Textile>), ('product_class', 'dress')]),
]

我需要获得产品变体的所有组合,如下所示:

# Note product_class is not really needed here.
[
   {
     <ProductAttribute: dress Color>: <AttributeOption: Black>},
     <ProductAttribute: dress Size>: <AttributeOption: S>,
     <ProductAttribute: dress Textile>: <AttributeOption: Cotton>,
   },
   {
     <ProductAttribute: dress Color>: <AttributeOption: Black>},
     <ProductAttribute: dress Size>: <AttributeOption: S>,
     <ProductAttribute: dress Textile>: <AttributeOption: Wool>,
   },
   .... 
   # this list should include all 24 possible combinations 3*2*4 = 24
   # 
]

我尝试使用itertools.product来获得我想要的结果,但没有找到运气。需要帮助!谢谢。


附加问题。

以下结果会是更好的设计吗?

[
   [
     {  
        "attribute": <ProductAttribute: dress Color>,
        "value": <AttributeOption: Black>
     },
     {
        "attribute": <ProductAttribute: dress Size>,
        "value": <AttributeOption: S>
     },
     {
        "attribute": <ProductAttribute: dress Textile>,
        "value": <AttributeOption: Cotton>
     }
   ],
   [
     {  
        "attribute": <ProductAttribute: dress Color>,
        "value": <AttributeOption: Black>
     },
     {
        "attribute": <ProductAttribute: dress Size>,
        "value": <AttributeOption: S>
     },
     {
        "attribute": <ProductAttribute: dress Textile>,
        "value": <AttributeOption: Wool>
     }
   ],
   .... 
   # this list should also include all 24 possible combinations 3*2*4 = 24
   # 
]

标签: pythondjangopython-3.xdjango-oscar

解决方案


推荐阅读