如何有效地统计字典列表中每个键的出现次数?

2024-10-05 10:06:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我想计算每个令牌的正/负文档频率。但是我的python脚本一直在运行早上好。可以你告诉我有什么问题吗?提前感谢。在

import numpy as np
positive_feature=[[{'a':2,'b':1},1],
                  [{'b':2,'c':1},1]
                 ]

negative_feature=[[{'e':2,'b':1},0]
                 ]
alltokens=['a','b','c','e']

dic=dict((t,i) for i,t in enumerate(alltokens))

vacabulary_size=len(dic)

positive_doc_frequency,negative_doc_frequency=np.zeros(vacabulary_size), np.zeros(vacabulary_size)

for t in alltokens:
    for x in positive_feature:
        if t in x[0].keys():
            positive_doc_frequency[dic[t]]+=1
    for x in negative_feature:
        if t in x[0].keys():
            negative_doc_frequency[dic[t]]+=1

根据alltokens列表的元素顺序,我想正数/负数的频率如下:

^{pr2}$

但是python脚本现在仍然在运行(从早上8:00到下午4:00),对我的脚本有什么优化吗?再次感谢。在

更新: 这个问题是误导性的,因为样本数据很差。我来纠正一下。在

输入:

alltokens=['a','b','c','e']
positive_feature=[[{'a':aa,'b':bb},1],
                  [{'b':vv,'c':cc},1]
                 ]

negative_feature=[[{'e':ee,'b':bb},0]
                 ]

我想要的输出是:

positive_doc_frequency=[1,2,1,0]
negative_doc_frequency=[0,1,0,1] 

“1,u”出现在“1,u”列表中,1次出现正频率,1次出现。在


Tags: in脚本forsizedocnpzerosfeature
2条回答
from itertools import chain
from collections import Counter
c = Counter(chain.from_iterable(d for d, x in positive_feature))
print(*sorted(c.items()))

这将列出positive_feature中的所有键,然后统计每个键的数量,然后打印计数。在

想要得到你想要的计数,就去做

^{pr2}$

我不知道为什么你的代码会运行那么长的时间,即使有一个大的数据集。在

在Python中,count occurrences of things有很多方法。我发现标准库中的collections.Counter是最快的方法(毫不奇怪,因为它只针对这个用例进行了优化)。在

在代码中使用collections.Counter将如下所示:

from collections import Counter

positive_doc_frequency = Counter()
negative_doc_frequency = Counter()

for t in alltokens:
    for x in positive_feature:
        positive_doc_frequency.update(x[0].keys())
    for x in negative_feature:
        negative_doc_frequency.update(x[0].keys())

相关问题 更多 >

    热门问题