计算 defaultdict 列表中的特定项目

Counting particular item in defaultdict list

所以这是我的 defaultdict

的结构
#x = {lead_id:[[month,pid,year]]
x={'123':[[1,9,2015],[2,9,2015]],'345':[[2,10,2015],[2,13,2014]],'159':[1,3,2015].....}

我在这本词典中有 1000 多个 lead_id。每个人都有 lists.In 的随机数,换句话说,相同的 lead_id 有重复但具有不同的月份或 pid 或年份。现在我想统计 1 月份的所有 lead_id,2015.I 如果根据它的出现次数是两倍或更多,我想把它算作两个。任何人都可以帮我弄清楚如何制作一个自动代码,以便它检查长度以及同年那个月发生的次数。

For example:
x={'123':[[1,3,2015],[2,5,2014],[1,5,2015]],'987':[[3,55,2014]],'456':[[1,37,2015]]}
count of jan 2015 = 3

这应该给出您的结果:

>>> day = 1
>>> year = 2015
>>> x = {'123':[[1,3,2015],[2,5,2014],[1,5,2015]],'987':[[3,55,2014]],'456':[[1,37,2015]]}
>>> sum([1 for k, v in x.iteritems() for i in v if i[0] == day and i[2] == year])
3

您可以对索引值进行条件判断。 date[0] 为 1 月。date[2] 为 2015 年

#!/usr/bin/python

x={'123':[[1,3,2015],[2,5,2014],[1,5,2015]],'987':[[3,55,2014]],'456':[[1,37,2015]]}

#Set query dates
query_month = 1 #jan
query_year = 2015 #year

#Set a counter
jan_counts = 0
for list_of_dates in x.values():
    for date in list_of_dates:
        if (date[0] == query_month) and (date[2] == query_year): 
            jan_counts += 1
print jan_counts
#3

你也可以用这个...

sum(1 for i in x for j in x[i] if j[0] == 1 and j[2] == 2015)