python3-学习搜索,这个非常简单的示例无法正常工作 [英] python3 - learning about searching, this very simple example does not work right

查看:70
本文介绍了python3-学习搜索,这个非常简单的示例无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是代码:

def findsort(something, alist):
    for item in alist:
        if item == something:
            return "found"
        else:
            return "not found"

def main():

    print(findsort(6, [3, 6, 1, 8, 11, 14]))

main()

由于某种原因,这与我认为应该起作用的方式不符.

for some reason, this doesn't work the way i thought it should work.

运行此命令时,它会显示未找到".但是,如果我将要查找的值更改为列表中的第一项,即3,它将返回为找到".

when i run this, it will say "not found." however, if i change the value i want to find to the first item in the list, the 3, it comes back as "found."

我已经尝试过使用字符串,并且得到了相同的结果.

i have tried this with strings, and i get the same results.

有人可以告诉我我在做什么错吗?

can someone please tell me what i am doing wrong?

推荐答案

因为如果在第一次迭代中该项目不匹配,则进入else分支,返回未找到",从而退出循环.

Because if in the first iteration the item doesn't match, you go into the else branch returning "not found", thus exiting the loop.

尝试一下:

def findsort(something, alist):
    for item in alist:
        if item == something:
            return "found"
    return "not found"

或简单地:

def findsort(something, alist):
    return "found" if something in alist else "not found"

这篇关于python3-学习搜索,这个非常简单的示例无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆