我得到了类似下面的API的回复,其中包含产品列表,其中一些产品是子产品,几乎就像一个捆绑产品。我想产生类似于下面的输出:
Main SKU 1
1 Sub Product(s)
Sub SKU - Something
Id
Main SKU 2
2 Sub Product(s)
Sub SKU - Something
Id
API数据如下所示:
{
"DisplayName": "Main SKU 1",
"Id": "1",
},
{
"DisplayName": "Main SKU 2",
"Id": "2",
},
{
"DisplayName": "Sub SKU - Something",
"Id": "3",
"ParentRef": {
"value": "1"
}
},
{
"DisplayName": "Sub SKU - Something Else",
"Id": "4",
"ParentRef": {
"value": "2"
}
},
{
"DisplayName": "Sub SKU - Something Else Again",
"Id": "5",
"ParentRef": {
"value": "2"
}
}
我想为控制台创建一个输出,如:
Main SKU 1
1 Sub Product(s)
Sub SKU - Something
Id
Main SKU 2
2 Sub Product(s)
Sub SKU - Something
Id
目前我正在遍历每个项目以获取Main的列表,然后再次使用Subs,但我正在努力将它们组合在一起。我的嵌套循环失控了,我确信我不应该多次迭代才能获得输出。
我只想指向正确的方向,我不希望我的代码是为我写的。
答案 0 :(得分:1)
您可以执行以下操作来创建一个树结构,其中包含dict
,其中key
将是Id of the parent
而value
将是list of its children
{1}}:
data = {}
for sku in _input
if 'ParentRef' not in sku:
data[sku['Id']] = []
for sku in bla:
if 'ParentRef' in _input:
data[sku['ParentRef']['value']].append(sku)
示例输入:
_input = [
{
"DisplayName": "Main SKU 1",
"Id": "1",
},
{
"DisplayName": "Main SKU 2",
"Id": "2",
},
{
"DisplayName": "Sub SKU - Something",
"Id": "3",
"ParentRef": {
"value": "1"
}
},
{
"DisplayName": "Sub SKU - Something Else",
"Id": "4",
"ParentRef": {
"value": "2"
}
},
{
"DisplayName": "Sub SKU - Something Else Again",
"Id": "5",
"ParentRef": {
"value": "2"
}
}
]
示例输出:
data = {
'2': [{
'DisplayName': 'Sub SKU - Something Else',
'ParentRef': {
'value': '2'
},
'Id': '4'
}, {
'DisplayName': 'Sub SKU - Something Else Again',
'ParentRef': {
'value': '2'
},
'Id': '5'
}],
'1': [{
'DisplayName': 'Sub SKU - Something',
'ParentRef': {
'value': '1'
},
'Id': '3'
}]
}
注意:这里我假设树的最大深度是2.如果它可能比这更深,这个解决方案将不起作用。
修改:谢谢@alexis;输入是内置的;请改用_input。
答案 1 :(得分:0)
我想响应存储在dict列表中。
这有效
res = [
{
"DisplayName": "Main SKU 1",
"Id": "1",
},
{
"DisplayName": "Main SKU 2",
"Id": "2",
},
{
"DisplayName": "Sub SKU - Something",
"Id": "3",
"ParentRef": {
"value": "1"
}
},
{
"DisplayName": "Sub SKU - Something Else",
"Id": "4",
"ParentRef": {
"value": "2"
}
},
{
"DisplayName": "Sub SKU - Something Else Again",
"Id": "5",
"ParentRef": {
"value": "2"
}
}
]
count = 0
for item in res:
parent_id = item.get('ParentRef',{}).get('value')
if parent_id:
for parent in res:
if int(parent['Id']) == int(parent_id):
count += 1
parent_Name = parent["DisplayName"]
print parent_Name
print count, "Sub Product (s)"
print item.get("DisplayName")
print "Id", item.get("Id")
输出
Main SKU 1
1 Sub Product (s)
Sub SKU - Something
Id 3
Main SKU 2
2 Sub Product (s)
Sub SKU - Something Else
Id 4
Main SKU 2
3 Sub Product (s)
Sub SKU - Something Else Again
Id 5
[Finished in 0.0s]