python - 可以在 django 中将选定值的列表添加在一起吗?

标签 python django calculation

例如,我将其作为 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 只有 total1,因此没有任何变化。 对于价格40,总共是两个,所以输出是80,对于价格45,总共是4 > 所以45*4=180

我想到了这种情况下出现的 javascript lodash ,并在 google 上搜索了一个名为 pydash 的东西,但不知何故我无法弄清楚如何使用它。

有谁能给我一个想法如何以最少的循环工作?

提前致谢。

最佳答案

我不确定 LDecimal 表示法,但您可以执行以下操作以获得所需的结果:

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/

相关文章:

django - 如何使用基于 django 类的 View 发送包含不同模型查询集的 json

algorithm - Rust 有没有计算乘积之和的好方法?

Java - 在除 double 时无法将 double 转换为整数

c++ - 为什么在C++中这个double值乘以2会出现计算错误?

python - 如何使用 ON DUPLICATE KEY UPDATE 正确增加变量

python - Qt 调试器在 mac 上使用错误的 python 版本

python - 如何在 Pandas 数据框中选择括号内的数据

python - socket,gethostbyaddr 的返回和写入文件如何拆分?

python - Django 没有反射(reflect) urls.py 的更改

django - ** 之后的 _filter_or_exclude() 参数必须是映射,而不是 ReverseManyRelatedObjectsDescriptor