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 に答える