例如,我将其作为 django
中的 list
[
{'price': Decimal('45.00'), 'total': 1L, 'quantity': 1}
{'price': Decimal('45.00'), 'total': 1L, 'quantity': 1}
{'price': Decimal('45.00'), 'total': 2L, 'quantity': 1}
{'price': Decimal('40.00'), 'total': 1L, 'quantity': 1}
{'price': Decimal('40.00'), 'total': 1L, 'quantity': 1}
{'price': Decimal('49.00'), 'total': 1L, 'quantity': 1}
]
我希望我的输出是将相同的价格加在一起,但还有另一个问题,即相同的价格乘以总数。 对于上面的示例,我想要的输出是
[
{'price': Decimal('180.00'), 'total': 4L, 'quantity': 1}
{'price': Decimal('80.00'), 'total': 2L, 'quantity': 1}
{'price': Decimal('49.00'), 'total': 1L, 'quantity': 1}
]
由于 price
49
只有 total
为 1
,因此没有任何变化。
对于价格40
,总共是两个,所以输出是80
,对于价格45
,总共是4
> 所以45*4=180
我想到了这种情况下出现的 javascript lodash
,并在 google 上搜索了一个名为 pydash
的东西,但不知何故我无法弄清楚如何使用它。
有谁能给我一个想法如何以最少的循环工作?
提前致谢。
最佳答案
我不确定 L
或 Decimal
表示法,但您可以执行以下操作以获得所需的结果:
from collections import defaultdict
lis = [
{'price': 45.00, 'total': '1L', 'quantity': 1},
{'price': 45.00, 'total': '1L', 'quantity': 1},
{'price': 45.00, 'total': '2L', 'quantity': 1},
{'price': 40.00, 'total': '1L', 'quantity': 1},
{'price': 40.00, 'total': '1L', 'quantity': 1},
{'price': 49.00, 'total': '1L', 'quantity': 1},
]
results = defaultdict(lambda: {'price':0, 'total':0, 'quantity':1})
for i in lis:
results[i['price']]['price'] += i['price']*int(i['total'].strip('L'))
results[i['price']]['total'] += int(i['total'].strip('L'))
print(list(results.values()))
这会导致:
[{'price': 180.0, 'total': 4, 'quantity': 1},
{'price': 80.0, 'total': 2, 'quantity': 1},
{'price': 49.0, 'total': 1, 'quantity': 1}]
关于python - 可以在 django 中将选定值的列表添加在一起吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48412871/