Home > front end >  How do you calculate the distribution of frequencies in a list in Python?
How do you calculate the distribution of frequencies in a list in Python?

Time:12-17

I may just be using the wrong words to search for this question, cause it doesn't strike me as that complicated, but can't seem to find an answer on StackOverflow

I have a list of strings;

 'Pelican Point',
 'Bridgetown',
 'Dunsborough',
 'Gelorup',
 'Ambergate',
 'Gelorup',
 'Yallingup Siding',
 'East Bunbury',
 ...
 'West Busselton',
 'Vasse',
 'Yallingup',
 'West Busselton',
 'Bunbury',
 'Collie',
 'Vasse',
 'Dunsborough',
 'Dunsborough',
 'Australind',
 'Busselton',
 'Busselton',
 'Abbey',
 'Dalyellup',
 'Quindalup'

And I would like to calculate;

  • the number of entries in the list that are unique
  • the number of entries that have between 5 and 2 entries
  • the number with more than 5 entries in the list

Is this possible?

CodePudding user response:

You can use collections.Counter to build a frequency map, where the key is a unique string, and the value is the frequency.

After that, your queries become straightforward.

CodePudding user response:

is this what you want? You can change the code inside "if-elif" condition according to your need.

lst = [ 'Pelican Point', 'Bridgetown', 'Dunsborough', 'Gelorup','Ambergate', 'Gelorup', 'Yallingup Siding', 'East Bunbury', 'West Busselton', 'Vasse', 'Yallingup', 'West Busselton', 'Bunbury', 'Collie', 'Vasse', 'Dunsborough', 'Dunsborough', 'Australind', 'Busselton', 'Busselton', 'Abbey', 'Dalyellup', 'Quindalup']
 
S = set(lst)
 
for e in S:
    c=lst.count(e)
    if(c==1):
        print("count for ",e, " is ",c)
    elif(c>=2 or c<=5):
        print("count for ",e, " is ",c)
    else:
        print("count for ",e," is ",c)
  • Related