How to sort a list by the number of occurrences? In Python

Asked

Viewed 247 times

1

Like, I have a list like this:

lista = [1,1,2,3,3,3]

And I want to order her to stay

lista = [3,3,3,1,1,2]

That is, the most occurring values would be at the beginning of the list, while the least occurring values at the end. I’ve tried several functions, but it didn’t work.

  • The list goes like this: list = [1,1,2,3,3,3] and I want it to be ordered by amount of occurrence, then it would be: list = [3,3,3,1,1,2]. I have no idea how to do this

2 answers

0

If you don’t want to use libraries, here’s an idea using dictionaries:

First I create a dictionary with occurrences

lista = [1,1,2,3,3,3]
ocorrencias = {}

for numero in lista:
    if numero in ocorrencias: #Se o numero ja esta no dicionario
        ocorrencias[numero] += 1
    else: #Se não está, adiciono em ocorrencias
        ocorrencias[numero] = 1
        #OU ocorrencias.update({numero:1})

>>> print ocorrencias
{1: 2, 2: 1, 3: 3}

Then create the sorted list from the occurrences dictionary

def pega_maior_ocorrencia(dicionario):
    maior_ocorrencia = 0
    chave = None
    for key, value in dicionario.iteritems(): #Python2.X
    #for key, value in d.items(): #Python3.X
        if value > maior_ocorrencia:
            maior_ocorrencia = value
            chave = key
    del dicionario[chave] #deleta do dict mesmo dentro da função
    return [chave]*maior_ocorrencia

lista_ocorrencias = []

for i in range(len(ocorrencias)):
    lista_ocorrencias += pega_maior_ocorrencia(ocorrencias)

>>> print lista_ocorrencias
[3, 3, 3, 1, 1, 2]

-2


Try this way:

from collections import Counter

lista = [1,1,2,3,3,3]

print [item for items, c in Counter(lista).most_common() for item in [items] * c]

# [3, 3, 3, 1, 1, 2]
  • Could you explain your answer ?

  • This "for items, c in Counter(list). most_common()" returns the values of your list and the amount of times it repeats, the rest tries to fill this list with * c or value x the amount of times the value repeats in your list. Go apologizing for the hasty explanation, but I’m leaving here. If you don’t solve it this way warn the error that I can help you once I return.

  • 1

    Edith your answer and put your explanation in it. You have not tested this code to say "If not resolved..." ?

  • It worked super well Raphael! Thank you very much friend, it served too much! Still did not know this library Counter. Thankful for the help!

Browser other questions tagged

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