纯粹是出于好奇心的缘故:
data = [
{
'quantity': Decimal(10),
'price': Decimal(1.25)
},
...
]
def func(data):
quantity = Decimal()
value = Decimal()
for item in data:
quantity += item['quantity']
value += item['quantity'] * item['price']
return quantity, value
func
的目的是在data
实现相同结果还有哪些其他方法?
答案 0 :(得分:1)
相同的想法,但使用迭代
def fun(data):
tons = sum(item['tons'] for item in data)
value = sum(item['tons']*item['price'] for item in data)
return tons, value
答案 1 :(得分:0)
这个怎么样:
data = [{'quantity': 10.0,'price': 1.25},{'quantity': 8.0,'price': 2.0}]
(quantity, value) = [sum(x) for x in zip(*[(x['quantity'],x['price']*x['quantity']) for x in data])]
# quantity = 18 and value = 28.5