从元组列表创建频率字典



我有

d = [(4, 1), (4, 1), (4, 1), (4, 1), (4, 3), (4, 2), (4, 2), (4, 4), (4, 1), (4, 3), (4, 1), (4, 1), (4, 2), (4, 1)] 

但是要大很多倍。

每个元组中的第一个数字是月份,第二个数字是事件数。我需要把每个月的事故数量加起来,并汇编每个月的总事故数量。到目前为止我有:

def histogram(L):
    y = {}
    for x in L:
        if x[0] in y.keys():
            y[x] = y[x] + x[1]
        else:
            y[x] = x[1]
    return y

我需要一个类似于y={4=24}(它不一定是字典)但是列表d中的数字范围是相当广泛的

当前输出为

{(4, 2): 2, (4, 4): 4, (4, 1): 1, (4, 3): 3}

感谢

您可以使用Counter。我还为您的示例添加了一些额外的数据。

d = [(4, 1), (4, 1), (4, 1), (4, 1), (4, 3), (4, 2), (4, 2), (4, 4), (4, 1), (4, 3), (4, 1), (4, 1), (4, 2), (4, 1), (5,1), (5,2)]
from collections import Counter
counter = Counter()
for x, y in d:
    counter[x]+=y

则CCD_ 1

您可以在此处使用带dict理解的itertools.groupby(考虑到数据按月份排序):

>>> from operator import itemgetter
>>> from itertools import groupby
>>> {k: sum(x for _, x in g) for k, g in groupby(d, key=itemgetter(0))}
{4: 24}

为了改进您的代码,您应该做的第一件事是删除.keys()调用(尽管这在这里无关紧要,因为我们只能有12个月的时间),因为简单的key in dct在O(1)时间内搜索关键字。另一个问题是使用x作为密钥,但应该使用x[1]作为密钥:

def histogram(L):
    y = {}
    for m, c in L:            #take the advantage of tuple unpacking
        y[m] = y.get(m, 0) + c

如果你确定你的dict中总是需要所有12个月,那么首先初始化所有的月:

def histogram(L):
    y = dict.fromkeys(range(1, 13), 0)
    for m, c in L:          
        y[m] += c

这应该能解决问题。

d=[(4,1),(4,1

def直方图(L):y={}对于L中的t:

month = t[0]
freq = t[1]
try :
  y[month] += freq
except KeyError:
  y[month] = 0
  y[month] += freq

返回y

打印(直方图(d))

我稍微更改了变量的名称

incidents = [(4, 1), (4, 1), (4, 1), (4, 1),
             (4, 3), (4, 2), (4, 2), (4, 4),
             (4, 1), (4, 3), (4, 1), (4, 1),
             (4, 2), (4, 1)]
inc_by_m = {}
for m, n in incidents:
    inc_by_m[m] = inc_by_m.get(m,0)+n
print inc_by_m
# {4:24}

直接的代码基于字典的.get()方法的可选参数(此处为0),get返回由强制参数索引的值(如果以前设置过),或者返回可选参数(如果没有设置)。

最新更新