By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
432,441 Members | 996 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 432,441 IT Pros & Developers. It's quick & easy.

count repeated elements in the list

P: 1
I am new to Python. I am trying to find a simple way of getting a count of the number of elements repeated in a file(of first column)
e.g file contain the following list(-First column contain IP address)

10.2.1.12 2 4
192.12.23.2 3 5
10.2.1.12 1 2
192.11.23.1 3 5
10.2.1.12 4 5
192.12.23.2 1 6

Output:
IP Address count( number of repeated of 1st column)
10.2.1.12 3
192.12.23.2 2
192.11.23.1 1
Apr 23 '14 #1
Share this Question
Share on Google+
2 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
If the order is not important, this can easily be done with a dictionary and dict method setdefault.
Expand|Select|Wrap|Line Numbers
  1. f = open("ip.txt")
  2. dd = {}
  3. for line in f:
  4.     lineList = line.split()
  5.     if lineList:
  6.         ip = lineList[0]
  7.     v = dd.setdefault(ip, 0)
  8.     dd[ip] += 1
  9.  
  10. f.close()
  11.  
  12. for key in dd:
  13.     print key, dd[key]
To display in order of count:
Expand|Select|Wrap|Line Numbers
  1. ipList = [(key, dd[key]) for key in dd]
  2. ipList.sort(key=lambda a: a[1])
  3. for item in ipList:
  4.     print item[0], item[1]
Apr 23 '14 #2

P: 7
You can use dictionaries for this
Expand|Select|Wrap|Line Numbers
  1. d=dict()
  2. fp=open("file.txt")
  3. for i in fp:
  4.     l=i.split()[0]
  5.     if l in d:
  6.         d[l] += 1
  7.     else:
  8.         d[l] = 1
  9.  
  10. print d.items()
  11.  
  12.  
May 2 '14 #3

Post your reply

Sign in to post your reply or Sign up for a free account.