[英]Python defaultdict, counting a list not working
So I have a list that I've sorted by date, and the number of records per date. 因此,我有一个按日期排序的列表,以及每个日期的记录数。 This is working fine, and in my print outs I can see the count. 一切正常,在打印输出中我可以看到计数。 However I need to build up an aggregate data structure from the one shown, and another later, and as such am trying to put together "temp". 但是,我需要从所示的一个和后面的另一个构建一个聚合的数据结构,因此我试图将“ temp”放在一起。
Why do I continually get 0
when appending into temp, when just above it in the print out, it shows me 4
? 为什么追加到temp时我总是不断得到0
,而在打印输出中恰好在它上面时却显示4
?
created = EmailAddress.objects.all().values_list('email', 'user__date_joined')
temp = defaultdict(list)
for key,group in itertools.groupby(created, key=lambda x: x[1].strftime('%Y%m%d')[:11]):
print 'Date of signup: ', key
print '# of signups: ', (sum(1 for _ in group))
temp[key].append(sum(1 for _ in group))
Output 输出量
Date of signup: 20150603
# of signups: 4
defaultdict(<type 'list'>, {'20150603': [0]})
group
is like a generator. group
就像一个发电机。 The first time you iterate over it, you "consume" all the values 第一次迭代时,您将“使用”所有值
You can just store the value in a variable 您可以将值存储在变量中
for key,group in itertools.groupby(created, key=lambda x: x[1].strftime('%Y%m%d')[:11]):
print 'Date of signup: ', key
num_signups = (sum(1 for _ in group))
print '# of signups: ', num_signups
temp[key].append(num_signups)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.