繁体   English   中英

在列表列表中查找字典值的中位数

[英]Find median of dictionary values in a list of lists

我遇到了麻烦。 我有以下列表:

listA = [
    [
        {u'source': u'manual', u'value': 10},
        {u'source': u'manual', u'value': 10},
        {u'source': u'manual', u'value': 20},
        {u'source': u'manual', u'value': 30},
        {u'source': u'manual', u'value': 10},
        {u'source': u'manual', u'value': 10},
        {u'source': u'manual', u'value': 10},
        {u'source': u'manual', u'value': 30}
    ],
    [
        {u'source': u'manual', u'value': 20},
        {u'source': u'manual', u'value': 50},
        {u'source': u'manual', u'value': 80},
        {u'source': u'manual', u'value': 60},
        {u'source': u'manual', u'value': 10},
        {u'source': u'manual', u'value': 10},
        {u'source': u'manual', u'value': 40},
        {u'source': u'manual', u'value': 30}
    ],
    [
        {u'source': u'manual', u'value': 60},
        {u'source': u'manual', u'value': 20},
        {u'source': u'manual', u'value': 40},
        {u'source': u'manual', u'value': 30},
        {u'source': u'manual', u'value': 20},
        {u'source': u'manual', u'value': 10},
        {u'source': u'manual', u'value': 50},
        {u'source': u'manual', u'value': 10}
    ]
]

What I want to do is to loop the nested list, extract the dictionary value (first position of first nested list, first position of second nested list, fist position of third nested list --> second position of first nested list, second position of第二个嵌套列表,第三个嵌套列表的第二个 position 等...),然后找到“x”position 值的中值。

谢谢!

您可以将列表理解与zip一起使用:

from statistics import median

[median(i['value'] for i in l) for l in zip(*listA)]
# [20, 20, 40, 30, 10, 10, 40, 30]

如果你想要 numpy 你可以使用numpy.median

import numpy as np

result = np.median([[i['value'] for i in l] for l in zip(*listA)], axis=1)
print(result)

Output

[20. 20. 40. 30. 10. 10. 40. 30.]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM