如何在嵌套列表中搜索元素并在 return 单个语句中搜索元素?

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

我有一个包含食物特征的列表列表。

我想要做的是搜索用户输入的食物名称,然后: 如果食物在列表中,打印有关食物的详细信息 如果食物不在列表中,打印一行以告知找不到食物

我已经设法创建使用 for 循环遍历列表和 return 食物的详细信息(如果找到食物)。 如果食物不在列表中,我正在努力做的是return单行说'Food not found'。

我已经尝试了一个 while 循环来基本上说 'while the food is not found, tell the user and ask for input again' 但这没有用 我已经尝试 'if food is not in the list' 打印出该语句,但是它似乎打印了与未找到食物一样多的迭代次数的同一行,或者即使食物在列表中它也打印了该行。

代码如下:

#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]}'

上面的工作是查找食物和打印详细信息。 当尝试 return 一行来表示找不到食物时,以下内容无效。

#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]}')

有多种方法可以实现您想要的行为。这是一个。

#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]}')

我建议构建一个以名称为关键字的字典,这样您就可以简单地 name in food_dict 看看您是否有该名称的食物。

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}")

一种选择是使用在找到食物时更新的标志,然后在循环之后检查标志值是否已更改。如果没有,则表示您没有找到食物,因此打印语句。

#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")

顺便提一下,使用 dict 结构对于管理此类数据非常有用