【问题标题】:Python: How to merge AND sum list values based on some criteriaPython:如何根据某些条件合并和求和列表值
【发布时间】:2017-02-01 13:00:11
【问题描述】:

我正在使用 python 3.6。我从这样的 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 }
]

现在,我的第一个目标是合并列表值并对“数量”值求和,其中“order_id”相同。所以,结果应该是这样的:

[
  { "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 }
]

曾经,我现在得到这个结果,我想合并这个新的列表值并对“数量”值求和,其中“item_id”是相同的。另外,我还想从结果中删除“order_id”,因为那样就无关紧要了。所以,结果应该是这样的:

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

我该怎么做?

【问题讨论】:

  • 你在编码方面做了什么?
  • 我在想一个带有嵌套条件的“for in”循环语句,但我认为这不是正确的方法,因为在每次出现的“for in”循环中我们都可以访问只有一个列表值。

标签: python arrays list api python-3.x


【解决方案1】:

首先,将get_order_id 定义为用于对输入进行排序的函数和itertools.groupby 的键(输入可能未按order_id 排序,groupby 在这种情况下无法正常工作)

分组后,只需重建一个简化字典列表,以 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)

结果:

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

【讨论】:

  • 感谢您的回答。它似乎有效,但是结果中的“item_id”具有“order_id”值而不是“item_id”值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-31
  • 2019-10-18
  • 2021-12-28
  • 2021-03-27
  • 2020-07-20
  • 1970-01-01
相关资源
最近更新 更多