【问题标题】:Element not found in list列表中未找到元素
【发布时间】:2019-05-25 16:08:03
【问题描述】:

我知道有类似的主题,我检查了每一个,但我仍然无法弄清楚我在这里做错了什么:

我有一个列表(待办事项)并想使用以下功能搜索 ID:

def searchID():
    todo_id_search = input('Please input ID:')
    if todo_id_search in todos:
        print(todo_id_search)
    else:
        print("ID not in list")

不知何故,它永远不会返回 ID(即使它在列表中)。应该可以搜索这样的ID还是我想错了?我正在使用 Python 3.7。

谢谢!

【问题讨论】:

  • 你应该包含一个语言标签(可能是python
  • 欢迎来到 Stack Overflow!当有足够的代码供我们复制、运行并获得您当前的结果时,最好回答有关特定代码的问题:minimal reproducible example。然后我们可以提供修复。所以。 todos 中有什么内容?

标签: python-3.x list search


【解决方案1】:

我认为这是由于您的input 数据与您正在检查的列表元素之间的datatype 不匹配造成的。

例如:如果你的todos中list的元素是integer数据,那么

todo_id_search = input('Please input ID:')

todo_id_search 始终是string,因为input 始终返回string 类型数据,因此您的if 代码块失败为stringint 无法比较,对于故障排除,您可以检查它的类型使用

print (type(todo_id_search))

确认您的列表todos 元素类型后,您可以在if 条件中使用int(todo_id_search)float(todo_id_search) 在用户输入数据(即todo_id_search)中执行必要的类型转换。

【讨论】:

  • 谢谢 - 我是盲人。更改为 str(todo_id_search),现在一切正常。
猜你喜欢
  • 1970-01-01
  • 2018-12-17
  • 2018-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多