好吧,您当前的代码不是很 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"