Home > Net >  How do I search nested lists for an element and return a single statement if the element?
How do I search nested lists for an element and return a single statement if the element?

Time:02-22

I have a list of lists containing characteristics of food.

What I want to be able to do is search take input from the user for the name of the food and then: IF the food is in the list, print details about the food IF the food is NOT in the list, print a single line to advise the food is not found

I have managed to create use a for loop to iterate over the list and return details of the food if the food is found. What I am struggling to do is return a SINGLE line to say 'Food not found' if the food is not in the lists.

I have tried a while loop to basically say 'while the food is not found, tell the user and ask for input again' but this hasnt worked I have tried 'if food is not in the list' print out the statement but that either seems to print the same line for as many iterations as the food is not found OR it prints the line even if the food is in the list.

Here is the code:

#initialising list 
food_list = ['banana', 10, 'f', 'yellow'], ['apple', 12, 'f', 'red'], ['pear', 60, 'f', 'green'], ['mango', 5, 'f', 'yellow'], ['lettuce', 3, 'v', 'green'], ['beans', 20, 'v', 'green'], ['red capsicum', 1, 'v', 'red'], ['corn', 20, 'v', 'yellow']
#requesting input to determine which food to look for
name = input('What food are you looking for? ')

#iterable loop to search through nested lists
for food in food_list:
    if name in food:
            if food[2] == 'f':
                print(f'All about', food[0], '--> FRUIT')
                print()
                print(f'Name:', food[0])
                print()
                print(f'Colour: ', food[3])
                print()
                print(f'Total available: {food[1]}')
            elif food[2] == 'v':
                print(f'All about', food[0], '--> VEGETABLE')
                print()
                print(f'Name:', food[0])
                print()
                print(f'Colour: ', food[3])
                print()
                print(f'Total available: {food[1]}'

The above works to find the food and print details. The below has not worked when trying to return a line to say a food isnt found.

#initialising list 
food_list = ['banana', 10, 'f', 'yellow'], ['apple', 12, 'f', 'red'], ['pear', 60, 'f', 'green'], ['mango', 5, 'f', 'yellow'], ['lettuce', 3, 'v', 'green'], ['beans', 20, 'v', 'green'], ['red capsicum', 1, 'v', 'red'], ['corn', 20, 'v', 'yellow']
#requesting input to determine which food to look for
name = input('What food are you looking for? ')
while name not in food_list:
    print('Sorry not found')
    name = input('What fruit are you looking for? ')

)

#initialising list 
food_list = ['banana', 10, 'f', 'yellow'], ['apple', 12, 'f', 'red'], ['pear', 60, 'f', 'green'], ['mango', 5, 'f', 'yellow'], ['lettuce', 3, 'v', 'green'], ['beans', 20, 'v', 'green'], ['red capsicum', 1, 'v', 'red'], ['corn', 20, 'v', 'yellow']
#requesting input to determine which food to look for
name = input('What food are you looking for? ')
for food in food_list:
    if name not in food:
        print('Sorry not here')
    elif name in food:
            if food[2] == 'f':
                print(f'All about', food[0], '--> FRUIT')
                print()
                print(f'Name:', food[0])
                print()
                print(f'Colour: ', food[3])
                print()
                print(f'Total available: {food[1]}')
            elif food[2] == 'v':
                print(f'All about', food[0], '--> VEGETABLE')
                print()
                print(f'Name:', food[0])
                print()
                print(f'Colour: ', food[3])
                print()
                print(f'Total available: {food[1]}')

CodePudding user response:

There are a bunch of ways to implement the behavior you want. Here's one.

#iterable loop to search through nested lists
index = -1
for n,food in enumerate(food_list):
    if name in food:
        index = n

if index == -1:
    print('Sorry not found')
else:
    food = food_list[index]
    if food[2] == 'f':
        print(f'All about', food[0], '--> FRUIT')
        print()
    elif food[2] == 'v':
        print(f'All about', food[0], '--> VEGETABLE')
        print()
    print(f'Name:', food[0])
    print()
    print(f'Colour: ', food[3])
    print()
    print(f'Total available: {food[1]}')

CodePudding user response:

I suggest building a dict keyed by names, so you can simply do name in food_dict to see if you have food by that name.

food_dict = {f[0]: f for f in food_list}  # {name: food}
food_types = {
    'f': "FRUIT",
    'v': "VEGETABLE",
}

while True:
    name = input('What food are you looking for? ')
    if name in food_dict:
        break
    print("Sorry, not found!")

[name, qty, ftype, color] = food_dict[name]
print(f"All about {name} --> {food_types[ftype]}\n")
print(f"Name: {name}\n")
print(f"Colour: {color}\n")
print(f"Total available: {qty}")

CodePudding user response:

One option is to use a flag that is updated when the food is found then after the loop you check if the flag value has changed. If it doesn't, it means that you don't found the food so you print the statement.

#initialising list 
food_list = ['banana', 10, 'f', 'yellow'], ['apple', 12, 'f', 'red'], ['pear', 60, 'f', 'green'], ['mango', 5, 'f', 'yellow'], ['lettuce', 3, 'v', 'green'], ['beans', 20, 'v', 'green'], ['red capsicum', 1, 'v', 'red'], ['corn', 20, 'v', 'yellow']
#requesting input to determine which food to look for
name = input('What food are you looking for? ')

# FLAG INITIALIZATION
flag = True

#iterable loop to search through nested lists
for food in food_list:
    if name in food:
            flag = False # HERE YOU CHANGE THE STATE OF THE FLAG
            if food[2] == 'f':
                print(f'All about', food[0], '--> FRUIT')
                print()
                print(f'Name:', food[0])
                print()
                print(f'Colour: ', food[3])
                print()
                print(f'Total available: {food[1]}')
            elif food[2] == 'v':
                print(f'All about', food[0], '--> VEGETABLE')
                print()
                print(f'Name:', food[0])
                print()
                print(f'Colour: ', food[3])
                print()
                print(f'Total available: {food[1]}')


# CHECK THE FLAG VALUE
if flag:
    print("Food Not Found")

Just to mention, using dict structure is way useful to manage this kind of data

  • Related