如何匹配字典中的两个值并合并结果 [英] How to match two values in dict and merge results
问题描述
说我有一些带有时间戳,价格和金额的数据.该数据可能非常大,并且匹配条件可能会出现在组中的任何位置.一个简单的示例如下所示:
Say I have some data with timestamps, prices and amounts. This data can be quite large and matching conditions could occur anywhere in the group. A simple example shown below:
[{"date":1387496043,"price":19.379,"amount":1.000000}
{"date":1387496044,"price":20.20,"amount":2.00000}
{"date":1387496044,"price":10.00,"amount":0.10000}
{"date":1387496044,"price":20.20,"amount":0.300000}]
我该如何对它进行排序,以便合并具有相同时间戳和相同价格的任何商品的金额?
How could I sort this so I combine the amounts of any item that has the same timestamp and same price?
所以结果看起来像(注意将2.0和0.3的量相加):
So the results look like (note the 2.0 and 0.3 amounts have been summed together):
[{"date":1387496043,"price":19.379,"amount":1.000000}
{"date":1387496044,"price":20.20,"amount":2.30000}
{"date":1387496044,"price":10.00,"amount":0.10000}]
我已经尝试了许多复杂的方法(使用Python 2.7.3),但是我不太了解python.我敢肯定有一个很好的方法来找到2个匹配的值,然后用新的数量更新一个并删除重复的值.
I've tried a number of convoluted methods (using Python 2.7.3), but I don't know python very well. I'm sure there's a good way to find 2 matching values and then updating one with new amount and removing the duplicate.
仅供参考,这是测试数据
FYI Here is the test data
L=[{"date":1387496043,"price":19.379,"amount":1.000000},{"date":1387496044,"price":20.20,"amount":2.00000},{"date":1387496044,"price":10.00,"amount":0.10000},{"date":1387496044,"price":20.20,"amount":0.300000}]
推荐答案
可能最好的方法是制作一个以(日期,价格)为键的字典.如果遇到重复的密钥,则可以合并字段以使密钥保持唯一性.
Probably the best way to do this would be to make a dictionary with (date, price) as keys. If you ever encounter a duplicate key, you can combine your fields to keep the keys unique.
def combine(L):
results = {}
for item in L:
key = (item["date"], item["price"])
if key in results: # combine them
results[key] = {"date": item["date"], "price": item["price"], "amount": item["amount"] + results[key]["amount"]}
else: # don't need to combine them
results[key] = item
return results.values()
对于您的示例,这将是一个有点混乱的O(n)解决方案,显然可以将其推广来解决您的最初问题.
This would be a slightly messy O(n) solution to your example that can obviously be generalized to solve your initial problem.
这篇关于如何匹配字典中的两个值并合并结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!