代码如下:
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()由于某些原因,这并不像我想的那样工作。
当我运行这个的时候,它会说“找不到”。但是,如果我将要查找的值更改为列表中的第一项,即3,它将返回为“found”。
我尝试过使用字符串,我得到了同样的结果。
有人能告诉我我哪里做错了吗?
发布于 2012-12-13 11:35:30
因为如果在第一次迭代中项不匹配,您将进入else分支,返回"not found",从而退出循环。
试试这个:
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"发布于 2012-12-13 12:17:25
@hyperboreus pointed out the cause of the error (在看到所有项之前执行的else分支)。
为了在排序的(“有序”)列表中查找项目,您可以使用执行二进制搜索(O(log(n))的bisect module而不是线性搜索item in alist (O(n)),例如,对于一百万个项目,二进制搜索将需要大约几十个操作而不是线性搜索的一百万个操作。
from bisect import bisect
findsort = lambda x, L: "found" if L and L[bisect(L,x) - 1] == x else "not found"https://stackoverflow.com/questions/13852484
复制相似问题