字典列表的Python集合计数器 [英] Python Collections Counter for a List of Dictionaries

查看:95
本文介绍了字典列表的Python集合计数器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个动态增长的数组列表,我想将类似的值加在一起.这是一个示例:

I have a dynamically growing list of arrays that I would like to add like values together. Here's an example:

{"something" : [{"one":"200"}, {"three":"400"}, {"one":"100"}, {"two":"800"} ... ]}

我希望能够将列表中的字典加在一起.因此,在这种情况下,对于键某物",结果将是:

I'd like to be able to add together the dictionaries inside the list. So, in this case for the key "something", the result would be:

["one":400, "three": 400, "two": 800]

或类似的东西.我熟悉Python的集合计数器,但是由于内容"列表包含字典,因此它将不起作用(除非我缺少某些内容). dict也正在动态创建中,因此如果没有dict,我将无法构建列表. EG:

or something to that effect. I'm familiar with the Python's collection counter, but since the "something" list contains dicts, it will not work (unless I'm missing something). The dict is also being dynamically created, so I can't build the list without the dicts. EG:

Counter({'b':3, 'c':4, 'd':5, 'b':2})

通常可以正常工作,但是一旦我尝试添加一个元素,先前的值就会被覆盖.我注意到了诸如此类的其他问题:

Would normally work, but as soon as I try to add an element, the previous value will be overwritten. I've noticed other questions such as these:

是否有任何pythonic方式将两个字典组合在一起(为同时出现在两个字典中的键添加值)?

列表字典中的Python项计数

但同样,列表中的对象是字典.

But again, the objects within the list are dicts.

推荐答案

我认为这可以满足您的要求,但是我不确定,因为我不知道该dict也正在动态创建,因此我可以不要在没有字典的情况下建立清单".仍然:

I think this does what you want, but I'm not sure because I don't know what "The dict is also being dynamically created, so I can't build the list without the dicts" means. Still:

input = {
    "something" : [{"one":"200"}, {"three":"400"}, {"one":"100"}, {"two":"800"}], 
    "foo" : [{"a" : 100, "b" : 200}, {"a" : 300, "b": 400}],
}

def counterize(x):
    return Counter({k : int(v) for k, v in x.iteritems()})

counts = {
    k : sum((counterize(x) for x in v), Counter()) 
    for k, v in input.iteritems()
}

结果:

{
    'foo': Counter({'b': 600, 'a': 400}), 
    'something': Counter({'two': 800, 'three': 400, 'one': 300})
}

我希望将sumCounter一起使用效率不高(与对字符串使用sum的效率非常低,以致Guido禁止使用它一样),但是我可能是错的.无论如何,如果遇到性能问题,可以编写一个创建Counter并在其上重复调用+=update的函数:

I expect using sum with Counter is inefficient (in the same way that using sum with strings is so inefficient that Guido banned it), but I might be wrong. Anyway, if you have performance problems, you could write a function that creates a Counter and repeatedly calls += or update on it:

def makeints(x):
    return {k : int(v) for k, v in x.iteritems()}

def total(seq):
    result = Counter()
    for s in seq:
        result.update(s)
    return result

counts = {k : total(makeints(x) for x in v) for k, v in input.iteritems()}

这篇关于字典列表的Python集合计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆