0

Hi guys I've been looking for sorting two lists from the highest value to the lowest.

I want to keep them synchronized. In my code, those lists are empty so users will be filling them with their input food and their values of calories. I have no clue how should I do that.

food = ["apple", "fries", "bread"]
food_calories = [150, 250, 175]

My requested output should be looking like

These are your today's calories
fries - 250 calories
bread - 175 calories
apple - 150 calories

I was trying to use zip and sorted but I'm not experienced with that particular syntax. My program is sort of daily food/activities manager with calories deficit/surplus.

1 Answers1

4

You go first with making pairs to keep the synchronisation between the values, then sort based on calories

food = ['apple', 'fries', 'bread']
food_calories = [150, 250, 175]
pairs = sorted(zip(food, food_calories), key=lambda x:x[1], reverse=True)

print(pairs) # [('fries', 250), ('bread', 175), ('apple', 150)]

If you want the 2 initial lists just re-use zip on all pairs

food, food_calories  = zip(*pairs)

print(food) # ('fries', 'bread', 'apple')
print(food_calories) # (250, 175, 150)

print("These are your today's calories")
for item, calorie in pairs:
  print(item, "-", calorie, "calories")
azro
  • 53,056
  • 7
  • 34
  • 70
  • What if my expected output print is pairs beneath itself? Am I supposed to print it with for cycle? – Vojtech Tilp Jun 21 '20 at 16:46
  • @VojtechTilp Please edit your initial post to show your expected output, we can't see different lines in comment – azro Jun 21 '20 at 16:47
  • @VojtechTilp I've edit my answer look – azro Jun 21 '20 at 18:47
  • Thanks for your effort helping me out. Appreciate that. – Vojtech Tilp Jun 21 '20 at 18:54
  • @VojtechTilp you can accept the answer so ;) (green tick on the left of it) – azro Jun 21 '20 at 20:55
  • I was messing around more and what if I want to add another food with calories? I tried it and it crashed. Is it because these lists became one list of tuples so those previous lists dont exist at all right now? To be more accurate I have few methods and one of them is adding user input into previous two lists. Sorry for bothering. – Vojtech Tilp Jun 23 '20 at 08:13
  • @VojtechTilp crash with what ? append new food to the new food list at the end ? Do `food, food_calories = zip(*pairs)` and `food, food_calories = list(food), list(food_calories)` to avoid them being tuple – azro Jun 23 '20 at 08:16
  • I understand, I didn't think of that, thanks for your support! :) – Vojtech Tilp Jun 23 '20 at 08:22