2014-04-23 43 views
0

嘿,夥計們我不擅長Python ......需要幫助!在列表中重複計數的次數

我有包含以下列表(IP地址)的文件,

10.2.1.12  
192.12.23.2  
10.2.1.12  
192.11.23.1 
10.2.1.12  
192.12.23.2 

預期輸出:

IP Address    count(number of repeated) 
10.2.1.12      3 
192.12.23.2      2    
192.11.23.1      1 
+0

使用字典 –

回答

1

使用collections.Counter

from collections import Counter 

with open('ip.txt') as f: 
    cnt = Counter(line.strip() for line in f) 
    print('{:<20} {}'.format('IP Address', 'count(number of repeated)')) 
    for ip, c in cnt.most_common(): 
     print('{:<20} {}'.format(ip, c))