Counting frequencies in a list

Asked

Viewed 807 times

3

I have the code below that works to count frequencies in a list. However, the output of this code is a NoneType and so I can’t use methods like .sort(), for example, to arrange the output to show in descending order.

I would like the result to come out in the form of a table or dictionary, but not NoneType.

def frequency(my_list): 

    # Creating an empty dictionary  
    freq = {} 
    for item in my_list: 
        if (item in freq): 
            freq[item] += 1
        else: 
            freq[item] = 1

    for key, value in freq.items(): 
        print (" % d : % d"%(key, value)) 

my_list =[1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2] 

final_list = frequency(my_list)
  • it is only its function to return what it calculated, with the command return - return freq in the last line, in case.

  • Thank you very much.

2 answers

2


When you make an expression like:

variavel = funcao()

The value that will be assigned to the variable will be the value returned by function. By default Python will return None. That is, if you do not explicitly make a return in its function indicating what you want it to return the returned value will be null.

Your function has no return, so the assigned value is null. To fix this, just specify which value should be returned:

def frequency(my_list): 
    freq = {} 
    for item in my_list: 
        if (item in freq): 
            freq[item] += 1
        else: 
            freq[item] = 1
    return freq

Thus the value of final_list will be the dictionary you created in freq.

Some tips that might be useful at some point in your studies:

1. The class dict has a method called get that can be used to return a value in a missing key. So, instead of doing:

if item in freq:
  freq[item] += 1
else:
  freq[item] = 1

You can just do:

freq[item] = freq.get(item, 0) + 1

2. In Python there is the class defaultdict that already implements all this logic of assigning a default value on missing keys in the dictionary. In the constructor you pass a calling object that will be invoked whenever it is necessary to set the missing value in the dictionary. The class itself int, without parameters, will return the value 0, so could do:

from collections import defaultdict

freq = defaultdict(int)

...
freq[item] += 1

So can do freq[item] += 1 without checking whether the key exists or not, because if it does not exist it will be created with the value 0 and already incremented in 1.

3. You can use the class Counter to calculate the frequency of values in a sequence.

  • Thank you very much. It helped a lot.

0

If it’s no problem, you could use the numpy module. Follow the code:

import numpy as np

def frequency(my_list): 
    freq = {}
    # Função "unique" retorna um array com todos elementos existentes
    # uma única vez (sem repetição).
    for item in np.unique(np.array(my_list)):
        # Pesquisa na lista a frequencia de cada elemento
        # A função "where" retorna um array com os índices onde ocorre o item.
        # A ideia é só usar o tamanho desse array que sabemos a frequência.
         freq[item] = np.where(np.array(my_list)==item)[0].shape[0]

    for key, value in freq.items(): 
        print (" % d : % d"%(key, value)) 

my_list =[1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2] 

final_list = frequency(my_list)

Exit:

  1 :  5
  2 :  4
  3 :  3
  4 :  3
  5 :  2

Browser other questions tagged

You are not signed in. Login or sign up in order to post.