【发布时间】: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