在列表中找不到元素

用户名

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

我有一个列表(待办事项),并希望使用以下功能搜索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。

谢谢!

极客桑布

我认为这是由于datatype您的input数据与要检查的列表元素之间不匹配引起的

例如:如果您列表中的元素todosinteger数据,则

todo_id_search = input('Please input ID:')

todo_id_search始终是一个stringinput总是返回string类型的数据,因此没有你if的代码块stringint所不能比拟的,对于故障排除您可以通过使用检查它的类型

print (type(todo_id_search))

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章