0

例如考虑文件:input.txt

  12
  23
  45
  45 
  45
  34
  34
  56
  12
  12
  12
  67
  89

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

  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 中编码以获得我期望的结果。这会有帮助??????

4

2 回答 2

7

使用collections.Counter

>>> 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)]
于 2013-09-04T07:34:02.670 回答
0
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]
于 2013-09-04T08:01:38.470 回答