我正在将这段代码用于我需要为朋友设计的小程序.问题是无法让它发挥作用.
我正在设计一个使用蔬菜和水果清单的程序.例如我的列表是:
smallist = [["apple", 2], ["banana", 3], ["strawberry",1]]
item = input("Please give the name of the fruit\n\n")
smallist.index(item)
print (smallist)
Run Code Online (Sandbox Code Playgroud)
问题是当我尝试找到让我们说苹果的索引时.我只是说苹果不存在.
smallist.index(item)
ValueError: 'apple' is not in list
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚为什么它不会向我展示苹果的价值,在这种情况下它将是2
apple是不是在 smallist.它位于包含在其中的嵌套列表中smallist.
你必须用循环搜索它:
for i, nested in enumerate(smallist):
if item in nested:
print(i)
break
Run Code Online (Sandbox Code Playgroud)
这里enumerate()为我们创建一个运行索引,同时循环,smallist这样我们就可以打印找到它的索引.
如果你想要做的是打印另一个值,我们不需要索引:
for name, count in smallist:
if name == item:
print(count)
break
Run Code Online (Sandbox Code Playgroud)
但是在这里使用字典会更容易:
small_dict = dict(smallist)
print(small_dict.get(item, 'Not found'))
Run Code Online (Sandbox Code Playgroud)