Dada una lista de valores flotantes, escriba un programa Python para ordenar la lista.
Ejemplos:
Input: list = ['1.2', '.8', '19.8', '2.7', '99.8', '80.7'] Output: ['.8', '1.2', '2.7', '19.8', '80.7', '99.8'] Input: list = [12.8, .178, 1.8, 782.7, 99.8, 8.7] Output: [0.178, 1.8, 8.7, 12.8, 99.8, 782.7]
Analicemos diferentes formas de resolver este problema.
Método n. ° 1: usar lambda
# Python code to sort list of decimal values # List initialization Input = [12.8, .178, 1.8, 782.7, 99.8, 8.7] # Using sorted and lambda Output = sorted(Input, key = lambda x:float(x)) # Printing output print(Output)
Producción:
[0.178, 1.8, 8.7, 12.8, 99.8, 782.7]
Método #2: Usar ordenados
# Python code to sort list of decimal values # List initialization Input = [12.8, .178, 1.8, 782.7, 99.8, 8.7] # Using sorted + key Output = sorted(Input, key = float) # Printing output print(Output)
Producción:
[0.178, 1.8, 8.7, 12.8, 99.8, 782.7]
Método #3: Usar ordenar
# Python code to sort list of decimal values # List initialization Input = [12.8, .178, 1.8, 782.7, 99.8, 8.7] # Using sort + key Input.sort(key = float) # Printing output print(Input)
Producción:
[0.178, 1.8, 8.7, 12.8, 99.8, 782.7]
Publicación traducida automáticamente
Artículo escrito por everythingispossible y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA