这是数据的数组:
输入数据:
list1 = [{'user': 1, 'coins': 2}, {'user': 18, 'coins': 8}, {'user': 1, 'coins': 1}, {'user': 3, 'coins': 1}, {'user': 5, 'coins': 1}, {'user': 7, 'coins': 0}, {'user': 18, 'coins': 0}]
预期结果:
list2 = [{'user': 1, 'coins': 3}, {'user': 18, 'coins': 8}, {'user': 3, 'coins': 1}, {'user': 5, 'coins': 1}, {'user': 7, 'coins': 0}]
因此,将有list1
,我们必须将硬币添加到类似的user
可以由用户识别的钥匙值。如果用户密钥具有相似的值为1(在上述情况下),则必须添加两个或多个用户的硬币,使其成为该用户硬币的总和。
在上面的示例中,我们可以看到该用户在2个不同的dict中添加了1个值,并在列表2中给出了总和。
This is the array of data:
Input Data:
list1 = [{'user': 1, 'coins': 2}, {'user': 18, 'coins': 8}, {'user': 1, 'coins': 1}, {'user': 3, 'coins': 1}, {'user': 5, 'coins': 1}, {'user': 7, 'coins': 0}, {'user': 18, 'coins': 0}]
Expected Outcome:
list2 = [{'user': 1, 'coins': 3}, {'user': 18, 'coins': 8}, {'user': 3, 'coins': 1}, {'user': 5, 'coins': 1}, {'user': 7, 'coins': 0}]
So, there will be list1
, and we have to add the coins to similar user
which can be identified by user key value. If user key have similar value that is 1 (in above case) then coins of both or multiple user must be added making it a total sum of that user coins.
In above example, we can see that user with 1 as value in 2 different dict got added and total sum was given in list 2.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
可以使用
collections.defaultDict
作为中间数据对象:或相似,使用 noreflow noreferrer“> <<<<<<代码> collections.counter 对象:
This can be easily done using a
collections.defaultdict
as intermediate data object:or similary, using a
collections.Counter
object: