Python Counter results to csv file

家住魔仙堡 提交于 2019-12-10 14:29:43

问题


this question is based on my pervious question: Python list help (incrementing count, appending)

I am able to create the following output when I do print c;

Counter({(u'New Zealand', 174.885971, -40.900557): 1, (u'Ohio, USA', -82.90712300000001, 40.4172871): 1})

Which is exactly how I want and now I would like to know how I can write this to a csv file. Each row will represent a new location, lon/lat, count.

I want to loop through the counter and access these parts: writer.writerow(["A", "B", "C"]);

A is the location like New Zealand, B is the lat/lon, C is the count of appearance,

How can I access count's results and get those desired parts? Thanks.


回答1:


A Counter is a subclass of the standard dict class; you can loop over the items in the dictionary with .iteritems() (python 2) or just .items() (python 3):

for key, count in your_counter.iteritems():
    location, lat, long = key
    writer.writerow([location, lat, long, count])

This writes four columns, with 2 separate columns for the latitude and longitude. If you want to combine those into one column, say, as a string with a slash between the two coordinates, just use string formatting:

for key, count in your_counter.iteritems():
    location, lat, long = key
    writer.writerow([location, '{}/{}'.format(lat, long), count])


来源:https://stackoverflow.com/questions/16173865/python-counter-results-to-csv-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!