1

您好我正在尝试在 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" 
4

5 回答 5

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" 
于 2013-10-28T16:44:49.653 回答
3

好吧,您当前的代码不是很 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"
于 2013-10-28T16:47:15.947 回答
1

您不需要编写搜索功能,只需使用

x in llist

更新:

def search_func(llist,x):
      for i in llist:
          if i==x:
             return True
      return False
于 2013-10-28T16:44:30.650 回答
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
于 2016-03-14T12:31:52.303 回答
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

效果最好。

于 2020-04-20T12:40:22.110 回答