【问题标题】:Aggregate a list in Python without using any libraries [closed]在不使用任何库的情况下在 Python 中聚合列表 [关闭]
【发布时间】:2023-02-10 00:44:42
【问题描述】:

我可以在不使用任何库的情况下获得以下输出吗? (以更短的方式)

输入:

items = [
  {'product': 'A', 'customer': 'A', 'count': 10},
  {'product': 'A', 'customer': 'B', 'count': 15},
  {'product': 'A', 'customer': 'C', 'count': 100},
  {'product': 'A', 'customer': 'A', 'count': 50},
]

输出:

items = [
  {'product': 'A', 'customer': 'A', 'count': 60},
  {'product': 'A', 'customer': 'B', 'count': 15},
  {'product': 'A', 'customer': 'C', 'count': 100},
]

这就是我所做的:

rs = []
for item in items:
  has = False
  for item1 in rs:
    if item1['product'] == item['product'] and \
      item1['customer'] == item['customer']:
      item1['count'] += item['count']
      has = True
      break
  if not has:
    rs.append(item)

【问题讨论】:

  • 你怎么没有工作?
  • 嗨@SiHa,它工作正常,我的朋友。实际上,我想要一个更短的代码 :D
  • 那么问题是off-topic,我会说
  • 缩短代码的方法是使用库。这里可能会进行一些轻微的清理,但我们不会在这里回答有关编码风格或优雅的问题。请尝试Code Review,先阅读他们自己的发帖指南。
  • 好吧,谢谢@KarlKnechtel。我要关闭它并立即尝试代码审查。

标签: python


【解决方案1】:

您可以使用临时字典,其中键是产品和客户的元组,因此可散列:

d = {}
for dct in items:
    key = (dct['product'], dct['customer'])
    dct['count'] += d.get(key, {'count': 0})['count']
    d[key] = dct

print(*d.values(), sep='
')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-10
    • 1970-01-01
    • 2023-02-26
    • 1970-01-01
    • 1970-01-01
    • 2012-08-19
    • 1970-01-01
    • 2014-07-21
    相关资源
    最近更新 更多