计算defaultdict列表中的特定项目

时间:2015-12-15 17:42:00

标签: python dictionary count default

所以这是我的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。每个都有随机数的列表。换句话说,相同的lead_id有重复但有不同的月份或pid或年份。现在我想计算2015年1月的所有lead_id。如果它的两倍或更多,我想把它算作两个。任何人都可以帮我弄清楚我如何制作一个自动代码,以便检查长度以及同年发生的月份的次数。

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

3 个答案:

答案 0 :(得分:5)

您也可以使用它......

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

答案 1 :(得分:2)

您可以对索引值执行条件。 1月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

答案 2 :(得分:1)

这应该给你的结果:

>>> 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
相关问题