Python - List of disordered and repeated colors


Hi, I'm doing a program that has a list of repeated and messy colors. I want to know which of those colors is the most repeated and in its case return the most repeated color and the number of times. There is a particularity, if there are several colors with the maximum number the priority of the list would be: blue, red, green and yellow.

To be able to do it I have thought about creating a function with 2 lists:

1 List with disordered and repeated colors.

2. List with priority.

This way I can go through the elements of list 2 and see how many times it repeats.

My program started like that but I got stuck and I do not know how to continue it:

def color_frecuente(lista):

    lista2 =["azul","rojo","verde","amarillo"]

    print lista2

    contador = 0

    for i in lista2:
        for j in colores:
            if i == j:
                contador += 1
        return (i,contador)

# bloque principal

colores = ['azul', 'rojo', 'verde', 'verde', 'verde', 'rojo', 'verde', 'verde', 'azul', 'amarillo', 'azul',
            'azul', 'verde', 'verde', 'verde', 'amarillo']
print color_frecuente(colores)

Can you help me out?

Thank you.

asked by FRANCISCO JAVIER VEGAS FERNAND 09.01.2018 в 16:46

3 answers


In the following code it is shown first to calculate a dictionary that stores the number of times each color is repeated, then we calculate the maximums, and if there are several colors that have the same amount of maximum we apply the maximum of that subset to your position.

def obtener_color_frecuente(colores, lista_prioridad):
    contador = {}
    for color in colores:
        if color in contador:
            contador[color] += 1 # incrementamos si existe el color
            contador[color] = 1 # creamos un nuevo item con el key del color y el valor inicial de 1
    m = max(contador.values()) # obtenemos el max de repeticiones
    color_seleccionado = [key for key, value in contador.items() if value == m] # seleccionamos los colores que cumplen con el maximo
    if len(color_seleccionado) > 1: # verificamos si existe mas de un maximo
        color_seleccionado = min(color_seleccionado, key= lambda x: lista_prioridad.index(x)) # obtenemos el elemento segun la prioridad
         color_seleccionado = color_seleccionado[0]
    return color_seleccionado, m

prioridad = ["azul","rojo","verde","amarillo"]
colores = ['azul', 'rojo', 'verde', 'verde', 'verde', 'rojo', 'verde', 'verde', 'azul', 'amarillo', 'azul',
        'azul', 'verde', 'verde', 'verde', 'amarillo']
print(obtener_color_frecuente(colores, prioridad))
answered by 09.01.2018 / 17:51

Here is a code that I hope will work for you.

colores = ['azul', 'rojo', 'verde', 'verde', 'verde', 'rojo', 'verde',
        'verde', 'azul', 'amarillo', 'azul', 'azul', 'verde', 'verde', 'verde', 'amarillo']

def color_frecuenta(lista):
  dicts = {} 
  count = 0
  for color in colores:
    #Lista con los colores, sin repetir
    if color not in dicts:
      dicts[color] = 0

  for color in colores:
    for key in dicts.keys():
      if key == color:
        dicts[key] +=1


answered by 09.01.2018 в 17:27

As you told @FjSevilla you can use collections.Counter () to generate basically a table of frequencies

from collections import Counter

colores = ['azul', 'rojo', 'verde', 'verde', 'verde', 'rojo', 'verde',
        'verde', 'azul', 'amarillo', 'azul', 'azul', 'verde', 'verde', 'verde', 'amarillo',

# Diccionario para configurar el orden adicional   
order={"azul":1, "rojo": 2, "verde": 3, "amarillo":4}

lista = sorted(list(Counter(colores).items()),key=lambda x: (-x[1], order[x[0]]))


The exit

[('azul', 8), ('verde', 8), ('rojo', 2), ('amarillo', 2)] # Lista completa
('azul', 8)                                               # El primer elemento
  • Modify the list of examples ( colores ) to fully test the order you expect
  • Counter(colores) generates a dictionary with each color and its number of occurrences
  • We transform it into a list with list()
  • And we sort it by sorted() , the function lambda sets how the order will be, first the number of occurrences descending -x[1] and second the order defined by the dictionary created especially order
answered by 09.01.2018 в 18:28