我有一个包含数字的大型.dat文件
1 2 89 75
72 66 14 99 1022 34111
14 67 82 77
3
7 8 9 ....
我想编写一个程序来检查每个数字的出现,直到40000,并写出一个文件,其中包含文件中存在的数量和次数。 我希望输出文件是这样的
1 1
2 1
14 2
答案 0 :(得分:1)
Counter
模块中的collections
类对于此类任务非常有用:
import collections
import itertools
with open("file.dat") as f:
tokens = itertools.chain.from_iterable(line.split() for line in f)
numbers = itertools.imap(int, tokens)
counts = collections.Counter(numbers)
for n in sorted(counts):
print(n, counts[n])