这个问题基于我以前的问题:Python list help (incrementing count, appending)
当我打印c;
时,我能够创建以下输出Counter({(u'New Zealand', 174.885971, -40.900557): 1, (u'Ohio, USA', -82.90712300000001, 40.4172871): 1})
这正是我想要的,现在我想知道如何将其写入csv文件。每行代表一个新位置,lon / lat,count。
我想遍历计数器并访问这些部分: writer.writerow([“A”,“B”,“C”]);
A就像新西兰一样, B是纬度/经度, C是出现次数,
如何访问计数结果并获取所需的部分?感谢。
答案 0 :(得分:8)
Counter
是标准dict
类的子类;你可以使用.iteritems()
(python 2)或只是.items()
(python 3)遍历字典中的项目:
for key, count in your_counter.iteritems():
location, lat, long = key
writer.writerow([location, lat, long, count])
这会写入四个列,其中包含2个独立的纬度和经度列。如果你想将它们组合成一列,比如说,作为一个字符串,在两个坐标之间有一个斜杠,只需使用字符串格式:
for key, count in your_counter.iteritems():
location, lat, long = key
writer.writerow([location, '{}/{}'.format(lat, long), count])