【问题标题】:Iterate through a list and find a match in Python [duplicate]遍历列表并在 Python 中找到匹配项 [重复]
【发布时间】:2021-04-07 09:12:16
【问题描述】:

刚开始使用 Python 并试图让它工作。我需要让用户输入 1 到 50 之间的数字,然后遍历数字列表并找到匹配项。我的代码不起作用,我不确定我做错了什么。你能帮帮我吗?

>>> numbers = [1,3,5,7,9,11,15,18,21,23,34,35,38,41,43,47,49]
>>> n=0
>>> while True:
    print("Type q to quit")
    answer = input("Guess a number between 1 a 50: ")
    if answer == "q":
        break
    if answer in numbers:
        print("Number " + answer + " was found! Congrats!")
        break
    elif answer not in numbers:
        print("Number " + answer + " was not found! Try again!")
        continue
    n += 1

【问题讨论】:

  • “我的代码不起作用”是什么意思?运行代码时会发生什么?你想让它做什么呢?你做过调试吗?如果是这样,您从可能导致问题的调试中学到了什么?如果您还没有进行任何调试,请阅读 this article 了解一些帮助您入门的提示。
  • answer是一个字符串,需要先转换成int
  • docs.python.org/3/library/functions.html#input - “然后该函数从输入中读取一行,将其转换为字符串(去除尾随换行符),然后返回。”..
  • 您不需要elif,只需else。如果answer in numbers 为假,那么answer not in numbers 必然为真。
  • 谢谢!我不知道我必须转换为 int。它现在正在工作。

标签: python list loops


【解决方案1】:

answer 是一个字符串,但 numbers 包含整数。将答案解析为 int:

numbers = [1,3,5,7,9,11,15,18,21,23,34,35,38,41,43,47,49]
# take this out of the loop since you don't need to print it every time
print("Type q to quit")
while True:
    answer = input("Guess a number between 1 and 50: ")
    if answer == "q":
        break
    # parse to int
    try:
        answer = int(answer)
    except ValueError:
        print("Please enter a valid number.")
        continue
    if answer in numbers:
        # use f-string to serialize number back into a string
        print(f"Number {answer} was found! Congrats!")
        break
    # don't need elif since answer must not be in numbers
    else:
        print(f"Number {answer} was not found! Try again!")

【讨论】:

  • 非常感谢!我不知道我必须将我的列表转换为 int。现在可以了。非常感谢您的帮助!
【解决方案2】:

answer 是一个字符串,而numbers 中的项目是ints。如果要使用in 运算符,则必须将它们转换为相同的类型。例如:

if int(answer) in numbers:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-31
    • 1970-01-01
    • 2022-11-20
    • 1970-01-01
    • 1970-01-01
    • 2020-01-07
    • 1970-01-01
    相关资源
    最近更新 更多