对Python字典数组按Key求均值

2021-09-07 作者:

[ENG TITLE]: Calculate Mean Value by Keys in Python List of Nested-Dicts  

[OR]: Calculate Mean Value by Attributes in Python List of Objects

让我们考虑这样一种情况:现在你有个对象叫做“学生”,他们有年龄、身高、体重等多种数值属性。如何在不关心具体属性名称的前提下,采取简便手段计算多名学生任意属性的均值?

Let’s think about this case, say you have an object that represents single student of a group, and each student has at least his/her age, height, weight, and more attributes like these.

Now how to easily calculate mean value of each attribute within the student group, without caring about attribute names?

或许挺容易的,那么再考虑一下,如果给每名学生加个成绩单,成绩单里放着多科目成绩。以下级对象之实例作为上级实例属性,形成嵌套关系,此时怎么算最简洁呢?

Well, if it’s not a tough challenge, then let’s talk about those nested attributes (object as an attribute)?

那么先来简化一下问题,把object简化成dict,反正这俩玩意本质类似,支持随意转化。

当不考虑嵌套字典的情况,那么问题就很容易解决。把多个字典,相同字段抽取出来,做成list再求均值就易如反掌。

Now let’s simplify the question, from Python object to Python dict, which is somehow similar stuff (and can be converted back and forth).

When it’s non-nested, which means every element of the input list is a single level depth dict, this is kinda easy anyway.

当然你可能不接受  testDataWithDicts 这个变量的形态,我标题党了,它不是个列表。不过如果你需要的话,把列表转换成字典,无非就是python最擅长的一句列表推导式;key值可以用对象的id,不重复的uuid或者自增数等等。关键,接下来的例子会让你意识到,为啥字典套字典,比列表套字典,在这里更实用。

Result is good. And if you don’t agree that the  testDataWithDicts is a LIST of dict, well it’s always easy to convert a list to a dict with a simple pythonic “list comprehension”, then you’re gonna know why a DICT of dict works better here in the following example.

而当这个解法遇到不讲武德的多层嵌套字典,就倒地不起。

Here comes the case with nested dicts:

Then we run into problems with no doubt, some attributes – the 2nd and 3rd level dicts cannot be calculated directly.

所以只好捡起20年前C语言老师让我们当堂练习的“递归”。只不过递归计算之前,要先把下层嵌套的dict,整理成跟最外层字典格式一致的样子 —— 例子中,最外层的看似无意义的“学号”刚好用上,完全不浪费。

Now it’s the time to consider what we used to do under this circumstance – recursion.

结果完全没悬念,打完收工。

And this works pretty well as expected.

 

 

原创文章,转载请注明: 转载自渔人小径

本文链接地址: 对Python字典数组按Key求均值

打赏 PayPal

文章的脚注信息由WordPress的wp-posturl插件自动生成

打赏 赞(0)
微信
支付宝
微信二维码图片

微信扫描二维码打赏

支付宝二维码图片

支付宝扫描二维码打赏

最近文章

标签

分享

发表评论

电子邮件地址不会被公开。 必填项已用*标注