Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count of each unique element in a list [duplicate]

Tags:

python

count

Say I have a list of countries

l = ['India', 'China', 'China', 'Japan', 'USA', 'India', 'USA']  

and then I have a list of unique countries

ul = ['India', 'China', 'Japan', 'USA']

I want to have a count of each unique country in the list in ascending order. So output should be as follows:

Japan 1
China 2
India 2
USA   2
like image 698
ComplexData Avatar asked Jun 07 '17 17:06

ComplexData


People also ask

How do you count unique items in a list?

You can use the combination of the SUM and COUNTIF functions to count unique values in Excel. The syntax for this combined formula is = SUM(IF(1/COUNTIF(data, data)=1,1,0)). Here the COUNTIF formula counts the number of times each value in the range appears.

How do you count the number of repeated elements in a list?

Method 2: Count occurrences of an element in a list Using count() The idea is to use the list method count() to count the number of occurrences.


2 Answers

You can use Counter from collections:

from collections import Counter

l = ["India", "China", "China", "Japan", "USA", "India", "USA"]

new_vals = Counter(l).most_common()
new_vals = new_vals[::-1] #this sorts the list in ascending order

for a, b in new_vals:
    print a, b
like image 164
Ajax1234 Avatar answered Nov 13 '22 23:11

Ajax1234


If you don't want to use a Counter you can count yourself (you already know the unique elements because you have ul) using a dictionary:

l = ['India', 'China', 'China', 'Japan', 'USA', 'India', 'USA'] 
ul = ['India', 'China', 'Japan', 'USA']

cnts = dict.fromkeys(ul, 0)  # initialize with 0

# count them
for item in l:
    cnts[item] += 1

# print them in ascending order
for name, cnt in sorted(cnts.items(), key=lambda x: x[1]):  # sort by the count in ascending order
    print(name, cnt)   
    # or in case you need the correct formatting (right padding for the name):
    # print('{:<5}'.format(name), cnt)  

which prints:

Japan 1
China 2
India 2
USA   2
like image 27
MSeifert Avatar answered Nov 13 '22 23:11

MSeifert