Last day I was trying for a method to find the count of unique items in a list. I found two solutions. Thought like it is worth to share here.
Method 1:
This method works only with python versions 2.7 and above. The collections library is not available in python versions less than 2.7.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
__author__ = 'Amal G Jose' | |
from collections import Counter | |
data_list = ['apple', 'apple', 'orange', 'mango', 'apple', 'grapes', 'banana', 'banana'] | |
count = Counter(data_list) | |
print count.items() | |
print "Count of apple : ", count['apple'] | |
print "Count of orange : ", count['orange'] | |
print "Count of banana : ", count['banana'] | |
print "Count of grapes : ", count['grapes'] | |
print "Count of mango : ", count['mango'] |
Method 2:
This is a very simple method using python dictionary. This will work in all versions of python.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
__author__ = 'Amal G Jose' | |
count = {} | |
data_list = ['apple', 'apple', 'orange', 'mango', 'apple', 'grapes', 'banana', 'banana'] | |
for value in data_list: | |
if value in count.keys(): | |
count[value] += 1 | |
else: | |
count[value] = 1 | |
print count | |
print "Count of apple : ", count['apple'] | |
print "Count of orange : ", count['orange'] | |
print "Count of banana : ", count['banana'] | |
print "Count of grapes : ", count['grapes'] | |
print "Count of mango : ", count['mango'] |