【问题标题】:Sorting Counter by year in Python [duplicate]在Python中按年份排序计数器[重复]
【发布时间】:2015-01-03 16:30:49
【问题描述】:

下面的代码计算 CSV 文件的一行中各个年份的出现次数。

import csv
from collections import Counter

out=open("meteors.csv", "r")
data=csv.reader(out)
data.next()
data=[row for row in data]
out.close()

year = [] 

for row in data:
    if row[2]=='':
        continue
    else:       
        year.append(row[2])

c = Counter(year)

print c

结果如下:

Counter ({'2012':15, '2004':10, '2008':4})

谁能给我一段代码,我可以添加以便按年份对结果进行排序?

【问题讨论】:

  • @abc: 不,这是尝试按 key 对字典进行排序。

标签: python counter


【解决方案1】:

试试这个:

sorted(c.items(),key=lambda x:x[0])

【讨论】:

  • 任何原因???投反对票???
  • 1) 错了。 2) 您是否访问过 此问题已在此处找到答案: 下的 2 个链接中的任何一个?
  • 你怎么能说错???
  • 恐怕没用。我在'print c'上方插入了
  • 你要试试print sorted(c.items(),key=lambda x:x[1])
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-26
  • 2021-09-01
  • 2021-11-29
  • 2022-08-11
  • 1970-01-01
  • 2021-12-28
  • 2022-01-16
相关资源
最近更新 更多