python - 从字典中获取所有具有列表值的组合(来自嵌套字典列表的笛卡尔积)
问题描述
我使用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
#
]
解决方案
推荐阅读
- angular - 我们如何在 Angular 4 应用程序中为特定的 html 页面导入条件 css 文件?
- android - 更改系统语言时,Android 复数无法正常工作
- scala - 如何在 Play 自己的代码中使用 Status
- javascript - javascript中的mouseChildren之类的东西
- spring - Spring Security - 从本地调用安全方法
- sip - SIP协议中的第三方注册
- ios - 使用 React 库时,xcode 中没有这样的文件或目录
- loops - 凿子中的中断语句
- c# - 使用 HTTPResponseMessage 连接多个字符串
- c# - 异步方法返回 500 Internal Server Error 以查看,即使它完成后也是如此