python - 在列表中查找项目时不应该出现 Elif 语句

标签 python python-3.x

所以我不确定我在这里做错了什么,但我想要它,所以如果他们输入拼写错误的“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/

相关文章:

python - 将多行 JSON 转换为 python 字典

python - 基于类的 View - 未调用 get 函数

python - 更好的设计以避免违反 Liskov 替换原则

python - django.core.exceptions.SuspiciousFileOperation : The joined path is located outside of the base path component

python - 以持久的方式存储 Python 的模拟结果?

Python - 如何将 1/0 转换为是/否(在 pandas.DataFrame 中)?

python - 为什么 else 在这种情况下不起作用

python - 识别时间序列何时通过图表和表格中的阈值

python - 从对象实例化内部的元组中提取值

python - 使用 Python 提取 JSON 文件中的嵌套项