Dada una lista de listas, la tarea es ordenar una lista en función del tamaño de las sublistas. Analicemos algunos métodos para hacer lo mismo. Método #1: Usar ordenar
Python3
# Python code to demonstrate # sort list of list # on the basis of size of sublist ini_list = [[1, 2, 3], [1, 2], [1, 2, 3, 4], [1, 2, 3, 4, 5], [2, 4, 6]] # printing initial ini_list print ("initial list", str(ini_list)) # sorting on basis of size of list ini_list.sort(key = len) # printing final result print("final list", str(ini_list))
Salida: lista inicial [[1, 2, 3], [1, 2], [1, 2, 3, 4], [1, 2, 3, 4, 5], [2, 4, 6]] final lista [[1, 2], [1, 2, 3], [2, 4, 6], [1, 2, 3, 4], [1, 2, 3, 4, 5]]
Método #2: Usar lambda
Python3
# Python code to demonstrate # sort list of list # on the basis of size of sublist ini_list = [[1, 2, 3], [1, 2], [1, 2, 3, 4], [1, 2, 3, 4, 5], [2, 4, 6]] # printing initial ini_list print ("initial list", str(ini_list)) # sorting on basis of size of list ini_list.sort(key = lambda x:len(x)) # printing final result print("final list", str(ini_list))
Salida: lista inicial [[1, 2, 3], [1, 2], [1, 2, 3, 4], [1, 2, 3, 4, 5], [2, 4, 6]] final lista [[1, 2], [1, 2, 3], [2, 4, 6], [1, 2, 3, 4], [1, 2, 3, 4, 5]]
Método #3: Usando ordenados
Python3
# Python code to demonstrate # sort list of list # on the basis of size of sublist ini_list = [[1, 2, 3], [1, 2], [1, 2, 3, 4], [1, 2, 3, 4, 5], [2, 4, 6]] # printing initial ini_list print ("initial list", str(ini_list)) # sorting on basis of size of list result = sorted(ini_list, key = len) # printing final result print("final list", str(result))
Salida: lista inicial [[1, 2, 3], [1, 2], [1, 2, 3, 4], [1, 2, 3, 4, 5], [2, 4, 6]] final lista [[1, 2], [1, 2, 3], [2, 4, 6], [1, 2, 3, 4], [1, 2, 3, 4, 5]]
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