Python 显示数字的最大计数的步骤 例如考虑文件: input.txt 12 23 45 45 45 34 34 56 12 12 12 67 89

Python 显示数字的最大计数的步骤 例如考虑文件: input.txt 12 23 45 45 45 34 34 56 12 12 12 67 89,python,Python,我需要的是一个代码,它将显示重复的最大次数,所以输出应该如下 12 4 45 3 34 2 23 1 56 1 67 1 89 1 我写的代码是: a = [] f = open("out","r") lines = f.readlines() for i in lines: j = i.split() a.append(j) print len(a) 它将总长度打印为13 如果有人能建议如何用python编写

我需要的是一个代码,它将显示重复的最大次数,所以输出应该如下

  12   4
  45   3
  34   2
  23   1
  56   1
  67   1
  89   1
我写的代码是:

 a = []
 f = open("out","r")
 lines = f.readlines()
 for i in lines:
    j = i.split()
    a.append(j)
 print len(a)
它将总长度打印为13

如果有人能建议如何用python编写代码以获得我期望的结果。使用


使用
collections.Counter
。使用python 2.7+。对于python 2.5+,请使用
collections.defaultdict
of
int
。@hughdbrown是的,但是可以假设关于python的问题(没有任何版本标记)将是2.7+或3+。在这种情况下,通过查看OP的
print
方法,我可以看到它不是3+。因此,我在逻辑上使用了Python 2的最新版本2.7.5。这是一个不错的解释。我只是说python现在已经不是单一的语言/库了。例如,在我的公司,一些新编写的2013版python应用程序采用python 2.7,其他应用程序采用python 2.6。我不认为这是独一无二的。
>>> l # assume you already read the list of numbers from the file.
[12, 23, 45, 45, 45, 34, 34, 56, 12, 12, 12, 67, 89]
>>> from collections import Counter
>>> Counter(l).most_common()
[(12, 4), (45, 3), (34, 2), (67, 1), (23, 1), (56, 1), (89, 1)]
with open('test.txt') as f:
v={}
for line in f:      
    if v.has_key(line):
            v[line][1]+=1
    else:
            v[line]=[line,1]
for k,v in v.items():
    print v[0],v[1]