我正在尝试使用 collections.counter 方法来计算每个键的值的数量。因此,当我遍历我的数据库时,我希望它保持对找到值的次数的计数。相反,它每次出现在数据库中时都会打印一个值。这是我使用的函数的代码:
def clusters(tweetLocation):
cityCount=None
cities = {"London":[51.50722, -0.12750], "New York":[-74.006605 ,40.714623]}
for k,v in cities.items():
if distance.distance(v, tweetLocation).miles < 50:
cityCount=k
else:
pass
return cityCount
脚本的代码:
city_counter=[]
while cursor.alive:#cursor reads all relevant values from the DB
try:
doc = cursor.next()
if not doc['coordinates']:
placeName = doc['place']['full_name']
loc = g.geocode(placeName)
time.sleep(0.15)
city_counter=Counter([clusters([loc])])
else:
places = doc['coordinates']['coordinates']
city_counter=Counter([clusters([places])])
except (ValueError, geocoders.google.GQueryError):
pass
except StopIteration:
break
print city_counter
所以宁愿返回类似的东西:
Counter({New York: 25, London: 15})
我得到:
Counter({None: 1})
Counter({None: 1})
Counter({New York: 1})
Counter({None: 1})
......
我以前从未使用过 collections.counter,但我认为它会返回值的总和。
谢谢