さて、あなたの現在のコードはあまり 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"