Skip to main content
 首页 » 编程设计

python之如何计算文本文件中给定数字的频率

2025年05月04日17unruledboy

如何计算文本文件中给出的数字的频率。文本文件如下。

     0 
     2 
     0 
     1 
     0 
     1 
     55 
     100 
     100 

我想要的输出如下

     0   3 
     1   2 
     2   1 
     55  1 
     100 2 

我试过了,没有成功

     def histogram( A, flAsList=False ): 
         """Return histogram of values in array A.""" 
         H = {} 
         for val in A: 
             H[val] = H.get(val,0) + 1 
         if flAsList: 
             return H.items() 
         return H 

任何更好的方法。提前致谢!

请您参考如下方法:

使用Counter .这是解决此类问题的最佳方法

from collections import Counter 
with open('file.txt', 'r') as fd: 
    lines = fd.read().split() 
    counter = Counter(lines) 
    # sorts items 
    items = sorted(counter.items(), key=lambda x: int(x[0])) 
    # prints desired output 
    for k, repetitions in items: 
        print k,'\t', repetitions 

输出:

0   3 
1   2 
2   1 
55  1 
100 2