Congratulations, your code is very nice.
There are a few little tricks you could use to make it shorter/simpler.
收集模块提供了一种称为缺省字标。 如果被搁置者有主人,则不必加以检查,那么,你可以设立一条不成文的起诉书,像固定的口号一样,除非它自动向你们提供一只空套,否则就没有钥匙。 因此,你可以改变
if ( adId in adDict ):
adDict[adId].add(userId)
else:
adDict[adId] = set(userId)
简单
adDict[adId].add(userId)
而且,不是
for row in reader:
adId = row[0]
userId = row[1]
您可以缩短时间。
for adId,userId in reader:
<><>Edit>: 正如帕克在评论中指出的,
for key, value in adDict.iteritems():
is the most efficient way to iterate over a dict, if you are going to use both
the key and value in the loop. In Python3, you can use
for key, value in adDict.items():
既然(a)项交还了一台拖车。
#!/usr/bin/env python
import csv
from collections import defaultdict
adDict = defaultdict(set)
reader = csv.reader(open("some.csv"), delimiter= )
for adId,userId in reader:
adDict[adId].add(userId)
for key,value in adDict.iteritems():
print (key, , , len(value))