嗨我试图在python中创建一个搜索功能,它通过一个列表并在其中搜索一个元素。
到目前为止我已经
了def search_func(list, x)
if list < 0:
return("failure")
else:
x = list[0]
while x > list:
x = list [0] + 1 <---- how would you tell python to go to the next element in the list ?
if (x = TargetValue):
return "success"
else
return "failure"
答案 0 :(得分:3)
您是说要查看某个元素是否在列表中?如果是这样,就不需要这样的功能。只需使用in
:
>>> lst = [1, 2, 3]
>>> 1 in lst
True
>>> 4 in lst
False
>>>
这种方法效率更高。
如果你 没有in
,我认为这样可行:
def search_func(lst, x):
return "success" if lst.count(x) else "failure"
答案 1 :(得分:2)
嗯,你当前的代码不是很Pythonic。而且有几个错误!你必须使用索引访问列表中的元素,纠正你的代码如下所示:
def search_func(lst, x):
if len(lst) <= 0: # this is how you test if the list is empty
return "failure"
i = 0 # we'll use this as index to traverse the list
while i < len(lst): # this is how you test to see if the index is valid
if lst[i] == x: # this is how you check the current element
return "success"
i += 1 # this is how you advance to the next element
else: # this executes only if the loop didn't find the element
return "failure"
...但请注意,在Python中,您很少使用while
来遍历列表,更自然,更简单的方法是使用for
,它会自动将变量绑定到每个元素,而不会必须使用索引:
def search_func(lst, x):
if not lst: # shorter way to test if the list is empty
return "failure"
for e in lst: # look how easy is to traverse the list!
if e == x: # we no longer care about indexes
return "success"
else:
return "failure"
但我们可以更多 Pythonic!您要实现的功能非常普遍,已经内置到列表中。只需使用in
来测试元素是否在列表中:
def search_func(lst, x):
if lst and x in lst: # test for emptiness and for membership
return "success"
else:
return "failure"
答案 2 :(得分:1)
您不需要编写搜索功能,只需使用
即可x in llist
更新
def search_func(llist,x):
for i in llist:
if i==x:
return True
return False
答案 3 :(得分:0)
您正在使问题变得更加复杂,同时在开始编码之前解决任何问题。您正在使用while循环等,有时可能会成为无限循环。您应该使用for循环来解决它。这比while循环更好。所以只需检查哪种情况对您有帮助。那就是你差不多完成了。
def search_func(lst,x):
for e in lst: #here e defines elements in the given list
if e==x: #if condition checks whether element is equal to x
return True
else:
return False
答案 4 :(得分:0)
def search(query, result_set):
if isinstance(query, str):
query = query.split()
assert isinstance(query, list)
results = []
for i in result_set:
if all(quer.casefold() in str(i).casefold() for quer in query):
results.append(i)
return results
效果最好。