2013-10-28 269 views
1

嗨我試圖在python中創建一個搜索功能,它通過一個列表並搜索其中的一個元素。搜索功能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

如果你想使自己的搜索,試圖實現二進制搜索算法中... –

+0

有一個在邏輯有些混亂......試圖通過線寫評論線,並與實際值的示例(即給'list'和'x'的值,並試圖弄清楚他們如何通過代碼進行更改) – Don

回答

2

那麼,你目前的代碼不是很Python的。而且有幾個錯誤!你必須使用的索引列表中進入電影的元素,可以矯正你的代碼,它看起來像這樣:

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" 

但我們可以 Python的!您想要實現的功能非常普遍,已經內置到列表中。只需使用in測試如果一個元素是一個列表裏:

def search_func(lst, x): 
    if lst and x in lst: # test for emptiness and for membership 
     return "success" 
    else: 
     return "failure" 
1

你不需要寫一個搜索功能,只需使用

x in llist 

更新:

def search_func(llist,x): 
     for i in llist: 
      if i==x: 
      return True 
     return False 
+0

是我知道的,但它對於一個任務,外教想要我們做,而不使用內置的python函數 – user2928929

+1

@ user2928929 - 「while」和「if」不是內置但是「in」是怎樣的? 'in'不是內置的。它是Python語法的一部分。 – iCodez

+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" 
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