Dada una lista que contiene elementos repetidos y no repetidos, la tarea es ordenar la lista dada en función de la frecuencia de los elementos. Analicemos algunos métodos para lo mismo.
Método #1: Usar colecciones.contador()
Python3
# Python code to demonstrate # sort list by frequency # of elements from collections import Counter ini_list = [1, 2, 3, 4, 4, 5, 5, 5, 5, 7, 1, 1, 2, 4, 7, 8, 9, 6, 6, 6] # printing initial ini_list print ("initial list", str(ini_list)) # sorting on basis of frequency of elements result = [item for items, c in Counter(ini_list).most_common() for item in [items] * c] # printing final result print("final list", str(result))
Producción:
initial list [1, 2, 3, 4, 4, 5, 5, 5, 5, 7, 1, 1, 2, 4, 7, 8, 9, 6, 6, 6] final list [5, 5, 5, 5, 1, 1, 1, 4, 4, 4, 6, 6, 6, 2, 2, 7, 7, 3, 8, 9]
Método #2: Usar iterables
Python3
# Python code to demonstrate # sort list by frequency # of elements from collections import Counter from itertools import repeat, chain ini_list = [1, 2, 3, 4, 4, 5, 5, 5, 5, 7, 1, 1, 2, 4, 7, 8, 9, 6, 6, 6] # printing initial ini_list print ("initial list", str(ini_list)) # sorting on basis of frequency of elements result = list(chain.from_iterable(repeat(i, c) for i, c in Counter(ini_list).most_common())) # printing final result print("final list", str(result))
Producción:
initial list [1, 2, 3, 4, 4, 5, 5, 5, 5, 7, 1, 1, 2, 4, 7, 8, 9, 6, 6, 6] final list [5, 5, 5, 5, 1, 1, 1, 4, 4, 4, 6, 6, 6, 2, 2, 7, 7, 3, 8, 9]
Método #3: Usando ordenados
Python3
# Python code to demonstrate # sort list by frequency # of elements ini_list = [1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 5, 5, 5, 4, 4, 4, 4, 4, 4] # printing initial ini_list print ("initial list", str(ini_list)) # sorting on basis of frequency of elements result = sorted(ini_list, key = ini_list.count, reverse = True) # printing final result print("final list", str(result))
Producción:
initial list [1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 5, 5, 5, 4, 4, 4, 4, 4, 4] final list [4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 2, 2, 2, 5, 5, 5, 1, 1]
Publicación traducida automáticamente
Artículo escrito por garg_ak0109 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA