基于值的字典分组/计数列表 [英] Group/Count list of dictionaries based on value

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

问题描述

我有一个令牌列表,看起来像:

I've got a list of Tokens which looks something like:

[{
    Value: "Blah",
    StartOffset: 0,
    EndOffset: 4
}, ... ]

我想做的是获取每个值在令牌列表中出现的次数.

What I want to do is get a count of how many times each value occurs in the list of tokens.

在VB.Net中,我会做类似...

In VB.Net I'd do something like...

Tokens = Tokens.
GroupBy(Function(x) x.Value).
Select(Function(g) New With {
           .Value = g.Key,
           .Count = g.Count})

Python中的等效功能是什么?

What's the equivalent in Python?

推荐答案

IIUC,您可以使用collections.Counter:

IIUC, you can use collections.Counter:

>>> from collections import Counter
>>> tokens = [{"Value": "Blah", "SO": 0}, {"Value": "zoom", "SO": 5}, {"Value": "Blah", "SO": 2}, {"Value": "Blah", "SO": 3}]
>>> Counter(tok['Value'] for tok in tokens)
Counter({'Blah': 3, 'zoom': 1})

(如果您只需要计数).如果要按值对它们进行分组,则可以使用itertools.groupby和类似的内容

if you only need a count. If you want them grouped by the value, you could use itertools.groupby and something like:

>>> from itertools import groupby
>>> def keyfn(x):
        return x['Value']
... 
>>> [(k, list(g)) for k,g in groupby(sorted(tokens, key=keyfn), keyfn)]
[('Blah', [{'SO': 0, 'Value': 'Blah'}, {'SO': 2, 'Value': 'Blah'}, {'SO': 3, 'Value': 'Blah'}]), ('zoom', [{'SO': 5, 'Value': 'zoom'}])]

尽管有点麻烦,因为groupby要求分组的术语是连续的,因此您必须首先按关键字排序.

although it's a little trickier because groupby requires the grouped terms to be contiguous, and so you have to sort by the key first.

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

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