python - 用 dicts 制作相同的列表,但只有唯一的记录
问题描述
list = [
{'status': u'Purchase', 'phantom': False, 'row_no': 1, 'product_id': 25872, 'standard_price': 14.0, 'qty': 1.0, 'cost': 14.0},
{'status': u'Purchase', 'phantom': False, 'row_no': 2, 'product_id': 25872, 'standard_price': 14.0, 'qty': 1.0, 'cost': 14.0},
{'status': u'Purchase', 'phantom': False, 'row_no': 3, 'product_id': 25875, 'standard_price': 14.0, 'qty': 1.0, 'cost': 14.0},
{'status': u'Purchase', 'phantom': False, 'row_no': 4, 'product_id': 25875, 'standard_price': 14.0, 'qty': 1.0, 'cost': 14.0},
{'status': u'Purchase', 'phantom': False, 'row_no': 5, 'product_id': 25875, 'standard_price': 14.0, 'qty': 1.0, 'cost': 14.0}
]
我有这个列表,里面有字典,你可以看到有两行带有product_id 25872
,树行带有product_id 25875
。
如何查看列表中的所有 dicts 并使用 dicts 制作相同的列表,但每个产品只有 1 行?并且'qty'
应该总结一下。
所以从这个列表中,我想得到像
list = [
{'status': u'Purchase', 'phantom': False, 'row_no': 1, 'product_id': 25872, 'standard_price': 14.0, 'qty': 2.0, 'cost': 14.0},
{'status': u'Purchase', 'phantom': False, 'row_no': 2, 'product_id': 25875, 'standard_price': 14.0, 'qty': 3.0, 'cost': 14.0},
]
解决方案
我认为在python 的理解的itertools.groupby
帮助下应该足够了。尝试这个:sum
list
from itertools import groupby
lst = [
{'status': u'Purchase', 'phantom': False, 'row_no': 1, 'product_id': 25872, 'standard_price': 14.0, 'qty': 1.0, 'cost': 14.0},
{'status': u'Purchase', 'phantom': False, 'row_no': 2, 'product_id': 25872, 'standard_price': 14.0, 'qty': 1.0, 'cost': 14.0},
{'status': u'Purchase', 'phantom': False, 'row_no': 3, 'product_id': 25875, 'standard_price': 14.0, 'qty': 1.0, 'cost': 14.0},
{'status': u'Purchase', 'phantom': False, 'row_no': 4, 'product_id': 25875, 'standard_price': 14.0, 'qty': 1.0, 'cost': 14.0},
{'status': u'Purchase', 'phantom': False, 'row_no': 5, 'product_id': 25875, 'standard_price': 14.0, 'qty': 1.0, 'cost': 14.0}
]
# Sort the list first, by `product_id`
lst = sorted(lst, key=lambda x:x['product_id'])
# This is where we will store our unique rows
agg = []
row_count = 1
for k,v in groupby(lst,key=lambda x:x['product_id']):
as_list = list(v)
as_list[0].update({
'qty': sum([row['qty'] for row in as_list]),
'row_no': row_count
})
agg.append(as_list[0])
row_count += 1
# Print the final result
print(agg)
注意:请不要list
用作变量名。
推荐阅读
- ruby-on-rails - GroupItem:Class 的未定义方法“属性”
- python - Python/Django 我如何做到只有对象/帖子的创建者才能看到他们帖子的删除/编辑功能按钮?
- c# - 无法将 System.Int64 类型的对象转换为 System.Int32 类型
- transactions - 为什么 Database.SqlQuery 会终止我使用 Database.BeginTransaction 启动的事务?
- python-3.x - Matplotlib - 如何绘制训练中每个时期的进度?
- javascript - 通过使用 toString 将数字转换为字符串来反转数字
- python - Python:用“/”斜杠符号分割字符串
- python - 如何理解 4x4 混淆矩阵?
- python - Dictionary 中的哪些键值未更新?
- ios - React Native ios 和 watchman