添加线性搜索

时间:2017-05-09 09:12:37

标签: python tkinter

尝试添加搜索功能以搜索此代码中的关键字:

button1 = tk.Button(f1, text='Year 12, Paper One', command=lambda:raise_frame(f2)).pack()
button2 = tk.Button(f1, text='Year 12, Paper Two', command=lambda:raise_frame(f3)).pack()
button3 = tk.Button(f1, text='Year 13, Paper One', command=lambda:raise_frame(f4)).pack()
button4 = tk.Button(f1, text='Year 13, Paper Two', command=lambda:raise_frame(f5)).pack()

tk.Label(f2, text="Year 12, Paper One").pack()
tk.Button(f2, text="HOME", command=lambda:raise_frame(f1)).pack()

tk.Label(f3, text="Year 12, Paper Two").pack()
tk.Button(f3, text="HOME", command=lambda:raise_frame(f1)).pack()
tk.Label(f4, text="Year 13, Paper One").pack()
tk.Button(f4, text="HOME", command=lambda:raise_frame(f1)).pack()
tk.Label(f5, text="Year 13, Paper Two").pack()
tk.Button(f5, text="HOME", command=lambda:raise_frame(f1)).pack()
raise_frame(f1)
root.mainloop()

这是我创建的当前搜索 - 这是正确的,我应该把它放在代码中吗?

def sequentialSearch(alist, item): 
     pos = 0 
     found = False 

     while pos < len(alist) and not found: 
         if alist[pos:pos+len(list(item))] == list(item):
             found = True 
         else: 
             pos = pos+1 

     return found 

1 个答案:

答案 0 :(得分:0)

您可能希望将代码放在按钮command的某处。

另外,如果我理解正确,你可以简单地缩短sequentialSearch功能

def sequentialSearch(alist, item):
    return item in alist

Python的in运算符检查item是否是alist的成员,我认为它只是对其执行顺序搜索。

示例:

alist = ['a','b','c']
item = 'b'
print(item in alist) # True
item = 'd'
print(item in alist) # False