First you have to join the values with their descriptions. The list, like this, does not have a mapping between product and 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 single-string 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']
But you have a list of strings where some are descriptions and others are values? At the very least, I would say that it is a very strange structure. Probably a list of tuples would better represent your data. You defined that list or got it from somewhere?
– Woss
is an exercise, I have to report the description and the value. I know I could use dictionary, key and value, but in that case I can’t, I have to do it using list only.
– Everton J. da Silva
Then change the structure that stores the data. Putting data of different natures in the same list will only add complexity to your problem and decrease semantics/readability/maintainability of your application
– Woss
Anderson, I understand that, , but it’s an exercise I’ve been given , and I wanted to solve it. know that in a real application, I won’t use it that way.
– Everton J. da Silva
Then put the whole exercise statement in the question so that the answers can bring you the best possible solution (and not just a solution from what you have already done)
– Woss