count repeated elements in the list

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jhn19833
    New Member
    • Apr 2014
    • 1

    count repeated elements in the list

    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
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    If the order is not important, this can easily be done with a dictionary and dict method setdefault.
    Code:
    f = open("ip.txt")
    dd = {}
    for line in f:
        lineList = line.split()
        if lineList:
            ip = lineList[0]
        v = dd.setdefault(ip, 0)
        dd[ip] += 1
    
    f.close()
    
    for key in dd:
        print key, dd[key]
    To display in order of count:
    Code:
    ipList = [(key, dd[key]) for key in dd]
    ipList.sort(key=lambda a: a[1])
    for item in ipList:
        print item[0], item[1]

    Comment

    • maya29988
      New Member
      • May 2014
      • 7

      #3
      You can use dictionaries for this
      Code:
      d=dict()
      fp=open("file.txt")
      for i in fp:
          l=i.split()[0]
          if l in d:
              d[l] += 1
          else:
              d[l] = 1
              
      print d.items()

      Comment

      Working...