Sort an alphanumeric list by number

-1

For study purposes, I have the following problem:

  

A list with grocery shopping with descriptions and values, you need to order more and more without losing the description.

Note: To sort the items I have to create the functions, I can not use them ready.

Example:

Lista = ["pao" , "2.50" , "queijo" , "3.00", "leite", "2.00"]
Lista_ordenada = ["leite","2.00" ,"pao" , "2.50" , "queijo" , "3.00"]

I thought about using bubble sort always comparing par numbers, but I could not.

    
asked by anonymous 04.06.2018 / 15:11

1 answer

3

First you have to merge the values with their descriptions. The list thus does not have a mapping between the product and the value. You could for example make tuples of two items: the product and its value.

minha_lista = ["pao" , "2.50" , "queijo" , "3.00", "leite", "2.00"]
lista_pares = []
for i in range(0, len(minha_lista), 2):  # Iterar sob a lista em passos de 2
    item = minha_lista[i]
    preco = minha_lista[i + 1]
    lista_pares.append((item, preco))

print(lista_pares)
# [('pao', '2.50'), ('queijo', '3.00'), ('leite', '2.00')]

Now, yes, you can use sorted :

lista_pares_ordenada = sorted(lista_pares, key=lambda tupla: float(tupla[1]))
print(lista_pares_ordenada)
# [('leite', '2.00'), ('pao', '2.50'), ('queijo', '3.00')]

And to turn the list back into a string-only format:

lista_ordenada = []
for tupla in lista_pares_ordenada:
    lista_ordenada.append(tupla[0])
    lista_ordenada.append(tupla[1])

print(lista_ordenada)
# ['leite', '2.00', 'pao', '2.50', 'queijo', '3.00']
    
04.06.2018 / 15:34