计算列表中重复的次数

时间:2014-04-23 13:57:49

标签: python-2.7

嘿伙计我不擅长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

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))