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

0

Type, I have a list like this:

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

And I want to order it 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 values less occurring at the end. I've tried several functions, but it did not work.

    
asked by anonymous 31.12.2017 / 21:54

2 answers

-2

Try this:

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]
    
01.01.2018 / 02:21
0

If you do not want to use libraries, here's an idea using dictionaries:

First I create a dictionary with the 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 I create the ordered list from the dictionary of occurrences

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]
    
10.08.2018 / 15:04