读书人

数组实现分组解决方案

发布时间: 2013-01-25 15:55:29 作者: rapoo

数组实现分组

 
carts=[{
"shopping_id": 173744,
"product_name": "aaa",
"product_code": "TL11111100014",
},{
"shopping_id": 173744,
"product_name": "aaa",
"product_code": "TL11111100018",
},{
"shopping_id": 173744,
"product_name": "bbb",
"product_code": "TL11111100013",
}]


怎么根据product_name 分组为2组数据
groupcarts=[
{'result':[{},{}]}
,
{'result':[{}]}
]
[解决办法]
groupcarts={};
for x in carts:
name = x['product_name']
if name in groupcarts:
groupcarts[name].append(x)
else:
groupcarts[name] = [x]

for x in groupcarts:
print x, groupcarts[x]

[解决办法]
引用:
Python code
groupcarts={};
for x in carts:
name = x['product_name']
if name in groupcarts:
groupcarts[name].append(x)
else:
groupcarts[name] = [x]

for x in groupcarts:
……

++

读书人网 >perl python

热点推荐