简体   繁体   English

Python:如何根据某些条件合并和求和列表值

[英]Python: How to merge AND sum list values based on some criteria

I'm using python 3.6.我正在使用 python 3.6。 I've some result from an API call like this:我从这样的 API 调用中得到了一些结果:

[
  { "order_id": 51128352, "item_id": 17811608, "amount": -1.74 },
  { "order_id": 51128352, "item_id": 17811608, "amount": 13.88 },
  { "order_id": 50290147, "item_id": 17811608, "amount": -1.74 },
  { "order_id": 50290147, "item_id": 17811608, "amount": 20.34 },
  { "order_id": 50320149, "item_id": 13397933, "amount": -5.78 },
  { "order_id": 50320149, "item_id": 13397933, "amount": 23.12 }
]

Now, my first goal is to merge the list values AND sum the "amount" value WHERE "order_id" is same.现在,我的第一个目标是合并列表值并对“数量”值求和,其中“order_id”相同。 So, the results should be something like this:所以,结果应该是这样的:

[
  { "order_id": 51128352, "item_id": 17811608, "amount": 12.14 },
  { "order_id": 50290147, "item_id": 17811608, "amount": 18.6 },
  { "order_id": 50320149, "item_id": 13397933, "amount": 17.34 }
]

Once, I get this result now I want to merge this new list values AND sum the "amount" value WHERE "item_id" is same.有一次,我现在得到了这个结果,我想合并这个新的列表值并总结“数量”值,其中“item_id”是相同的。 PLUS I also want to remove "order_id" from the result, since then it would be irrelevant. PLUS 我还想从结果中删除“order_id”,从那时起它就无关紧要了。 So, the results should be something like this:所以,结果应该是这样的:

[
  { "item_id": 17811608, "amount": 30.74 },
  { "item_id": 13397933, "amount": 17.34 }
]

How should I do it?我该怎么做?

First, define get_order_id as a function used to sort your input and as a key to itertools.groupby (input could be unsorted order_id-wise and groupby wouldn't work properly in that case)首先,将get_order_id定义为用于对输入进行排序的函数和itertools.groupby的键(输入可能是未排序的 order_id-wise 并且groupby在这种情况下无法正常工作)

Once grouped, just rebuild a list of simplified dicts, with order_id and amount as keys, and the sum of amounts for amount value.分组后,只需重建一个简化字典列表,以order_idamount为键,以及amount值的金额总和。

l = [
  { "order_id": 51128352, "item_id": 17811608, "amount": -1.74 },
  { "order_id": 50290147, "item_id": 17811608, "amount": -1.74 },
  { "order_id": 50290147, "item_id": 17811608, "amount": 20.34 },
  { "order_id": 50320149, "item_id": 13397933, "amount": -5.78 },
  { "order_id": 51128352, "item_id": 17811608, "amount": 13.88 },
  { "order_id": 50320149, "item_id": 13397933, "amount": 23.12 }
]

import itertools

get_order_id = lambda x : x["order_id"]

result = [{'amount':  sum(x['amount'] for x in r), 'item_id' : k} 
          for k,r in itertools.groupby(sorted(l,key=get_order_id),key=get_order_id)]

print(result)

result:结果:

[{'amount': 18.6, 'item_id': 50290147}, {'amount': 17.34, 'item_id': 50320149}, {'amount': 12.14, 'item_id': 51128352}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM