例如考虑文件: 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中编码以获得我期望的结果。它会有所帮助??????
答案 0 :(得分:7)
>>> 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)]
答案 1 :(得分: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]