发布于 2025-01-23 06:31:29 字数 671 浏览 1 评论 0原文

这是数据的数组:

输入数据:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

凹づ凸ル 2025-01-30 06:31:29

可以使用 collections.defaultDict 作为中间数据对象:

import collections
dd = collections.defaultdict(int)
for d in list1:
    dd[d['user']] += d['coins']
list2 = [{'user': user, 'coins': coins} for user, coins in dd.items()]

或相似,使用 noreflow noreferrer“> <<<<<<代码> collections.counter 对象:

cntr = collections.Counter()
for d in list1:
    cntr[d['user']] += d['coins']
list2 = [{'user': user, 'coins': coins} for user, coins in cntr.items()]

This can be easily done using a collections.defaultdict as intermediate data object:

import collections
dd = collections.defaultdict(int)
for d in list1:
    dd[d['user']] += d['coins']
list2 = [{'user': user, 'coins': coins} for user, coins in dd.items()]

or similary, using a collections.Counter object:

cntr = collections.Counter()
for d in list1:
    cntr[d['user']] += d['coins']
list2 = [{'user': user, 'coins': coins} for user, coins in cntr.items()]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文