Python计数器结果到csv文件 [英] Python Counter results to csv file
问题描述
这个问题是基于我的前提问题: Python列表帮助(递增计数,追加)
this question is based on my pervious question: Python list help (incrementing count, appending)
我可以在打印c时创建以下输出:
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})
这是我想要的,现在我想知道如何写一个csv文件。每一行将代表一个新的位置,lon / lat,count。
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.
我想循环访问计数器并访问这些部分:
writer.writerow([A,B,C]);
I want to loop through the counter and access these parts: writer.writerow(["A", "B", "C"]);
A是新西兰的位置,
B是lat / lon,
C是外观计数,
A is the location like New Zealand, B is the lat/lon, C is the count of appearance,
如何访问count的结果并获取所需的部件?感谢。
How can I access count's results and get those desired parts? Thanks.
推荐答案
A 计数器
c $ c> dict class;你可以用 .iteritems()
(python 2)或 .items()
(python 3):
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])
这篇关于Python计数器结果到csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!