那麼,你目前的代碼不是很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"
如果你想使自己的搜索,試圖實現二進制搜索算法中... –
有一個在邏輯有些混亂......試圖通過線寫評論線,並與實際值的示例(即給'list'和'x'的值,並試圖弄清楚他們如何通過代碼進行更改) – Don