所以我不确定我在这里做错了什么,但我想要它,所以如果他们输入拼写错误的“bloof”,它会说“找不到项目”,但这里有 elif 语句,即使你输入“血”,它仍然称之为“找不到元素”
如果你去掉 elif 语句,输入“blood”会调用该项目,但使用 elif 语句它总是说“找不到项目”
shopitemsF = ["Ghostblade: 150 Damage, Cost: 700", "Thunderblade: 120 Damage, Cost: 300",
"Bloodcursed Sword: 200 Damage, Cost: 950"]
shopchoice = input("Please choose an item from the shop by typing part of its name: ")
shopchoice = shopchoice.title()
for text2 in shopitemsF:
if shopchoice in text2:
print(text2)
elif shopchoice not in text2:
print("Item not found.")
shopchoice = input("Please pick another item? ")
最佳答案
您的方法和下面的解决方案修复了您的方法中的错误,但无法扩展。
found = False
for text2 in shopitemsF:
if shopchoice in text2:
found = True
break
if not found:
print("Item not found.")
shopchoice = input("Please pick another item? ")
else:
print("Item found")
我说的不是 scalabe,因为如果您在 shopitemsF
中有 N 个项目并且每个项目的平均长度为 M
,则此搜索将是 O(NM) - 可管理小 N 和小 M,但有数千条记录,速度会很慢。
关于python - 在列表中查找项目时不应该出现 Elif 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44252230/