简体   繁体   English

Python Counter结果为csv文件

[英]Python Counter results to csv file

this question is based on my pervious question: Python list help (incrementing count, appending) 这个问题基于我以前的问题: Python列表帮助(递增计数,追加)

I am able to create the following output when I do print c; 我打印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. 这正是我想要的,现在我想知道如何将其写入csv文件。 Each row will represent a new location, lon/lat, count. 每行代表一个新位置,lon / lat,count。

I want to loop through the counter and access these parts: writer.writerow(["A", "B", "C"]); 我想遍历计数器并访问这些部分:writer.writerow([“A”,“B”,“C”]);

A is the location like New Zealand, B is the lat/lon, C is the count of appearance, A是新西兰的位置,B是lat / lon,C是外观的数量,

How can I access count's results and get those desired parts? 如何访问计数结果并获得所需的部分? Thanks. 谢谢。

A Counter is a subclass of the standard dict class; Counter是标准dict类的子类; you can loop over the items in the dictionary with .iteritems() (python 2) or just .items() (python 3): 你可以使用.iteritems() (python 2)或只是.items() (python 3) .items()字典中的项目:

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. 这会写入列,纬度和经度分别为2列。 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])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM