0

If I have a nested list as follows:

foods = [['Category', 'Carbs', 'Calories'], ['SWEET POTATO', '23.4', '100'], ['TOMATOES', '5.1', '23'], ['BEETS', '16.28', '65'], ['LETTUCE', '2.23', '13']]

I want to find and print the sublist with the lowest Calorie count. I have tried the following:

    lowcal = foods[0]
for x in foods:
    if x[2] < lowcal[2]:
        lowcal = x
    else:
        continue
print (lowcal)

But I am getting the wrong output, I am getting: `['SWEET POTATO', '23.4', '100']

When I should be getting: ['LETTUCE', '2.23', '13']

2 Answers 2

1

You can use min() on your list with key as third element:

min([x for x in foods[1:]], key=lambda x: int(x[2]))
Sign up to request clarification or add additional context in comments.

Comments

1

Your problem is that your values for Carbs and Calories are strings (you have them in quotes!), rather than integers. Also, you start with lowcal = foods[0] which is your headers, not a food with calories and carbs. I'd suggest the following:

foods = [
    ['Category', 'Carbs', 'Calories'],
    ['SWEET POTATO', '23.4', 100],
    ['TOMATOES', '5.1', 23],
    ['BEETS', '16.28', 65],
    ['LETTUCE', '2.23', 13]
]
lowcal = foods[1]
for x in foods[2:]:
    if int(x[2]) < int(lowcal[2]):
        lowcal = x
>>> print (lowcal)
['LETTUCE', '2.23', 13]

Victory! Hope that helps, happy coding!

2 Comments

The problem is for this task I am working on a .csv file given to me so I cannot remove the quotes around the calorie integers. I have to convert them to ints in my code but I'm not sure how to do that.
ah, you just presented it as a list of lists. In fact, you said you have a list of lists, not a csv. I see you chose a correct answer already, but I modified mine to work as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.