Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
This post was edited and submitted for review 2 years ago and failed to reopen the post:
Duplicate This question has been answered, is not unique, and doesn’t differentiate itself from another question.
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(3)
您可以利用
group> groupby
在Itertools模块中。因此,基本上,您可以根据
“ CAT_ID”
的值对字典进行分组。在“ for循环”中,您将获得第一个字典并将其添加到最终结果列表中,然后对于组中的其余字典就存在,您只需增加“ tocks”
的值。要注意的一件事是,您的数据应该已经通过这种方法进行对。如果不是,您需要先排序它。这就是
groupby
的工作方式。You can take advantage of
groupby
in itertools module. So basically you group the dictionaries based on the value of the"cat_id"
. In the for loop, you get the first dictionary and add it to the final result list, then for the rest of the dictionaries exist in the group, you just increment the value of"items"
.One thing to note is that your data should already be sorted with this approach. If not you need to first sort it. This is how
groupby
works.我将使用 pandas dataFrame
new_dict
的输出将是I would use pandas dataframe
the output for
new_dict
will bepython为您提供了 defaultdict 的简单直截了当的答案
,最后,您的 output_list 将具有预期的结果。
Python is providing you the easy and straight forward answer with the defaultdict
Finally, your output_list will have the expected result.