如何计算许多对象的总和

时间:2015-02-05 23:05:10

标签: python django

有代码:

ids = []
menu = {}
for offer in customer_order.split(';'):
    id, count = offer.split(':')
    ids.append(id)
    menu[int(id)] = int(count)
mList = Goods.objects.filter(id__in=ids,
                             kind_cost=1).values('id', 'cost')
for item in mList:
    id = item['id']
    cost = item['cost']
    menu[id] = menu[id] * cost
return sum(menu.values())

customer_order是一个字符串,包括:' 32:5; 45:2; 555:23'等等。

我的问题:我确信有最好的解决方案来实现结果。任何人都可以帮我寻找解决方案吗?请分享链接以了解如何改进代码

TNX!

UPD:我需要总结所有商品的成本

1 个答案:

答案 0 :(得分:0)

看起来customer_order是一个看起来像dict的字符串(可能是JSON?)如果它是JSON你应该使用json模块来解析它,但我会继续在假设它实际上是一个本地python字典对象作为字符串。

import ast

customer_order = ast.literal_eval(customer_order)
# makes this into an ACTUAL dict...

mList = Goods.objects.filter(id__in=customer_order.keys(),
                              kind_cost=1).values('id', 'cost')
# mList is now a list of dicts, each dict has keys `id` and `cost`

mList = dict([k.values() for k in mList])
# mList is now a single dict with id:cost pairings

# As a lengthy aside, you might be better off just doing:
#
# # mList = Goods.objects.filter(id__in=customer_order.keys(),kind_cost=1)
# # mList = {item.id:item.cost for item in mList}
#
# I find that must easier to read. If your items have a huge number of 
# columns, of course, this will vastly increase your query time. YMMV.

result = [qty * mList[id] for id,qty in customer_order.items()]

如果customer_order实际上只是看起来像key1:value1;key2:value2的键值配对,那么您将不得不进行一些预处理。

customer_order = {keyvalue.split(":") for keyvalue in customer_order.split(";")}