5

这个问题是基于我以前的问题: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 文件。每行将代表一个新位置,经度/纬度,计数。

我想遍历计数器并访问这些部分: writer.writerow(["A", "B", "C"]);

A是新西兰的位置,B是纬度/经度,C是出现次数,

如何访问 count 的结果并获得所需的部分?谢谢。

4

1 回答 1

8

ACounter是标准类的子dict类;.iteritems()您可以使用(python 2)或仅使用(python 3)遍历字典中的项目.items()

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])
于 2013-04-23T15:54:21.020 回答