2016-11-18 3 views
0

私の割り当てでは、単語が文字列内にあればその文字列の単語のインデックスを返す関数を作成し、単語は、文字列Pythonで文字列の単語をインデックスする関数を作成する

bigstring = "I have trouble doing this assignment" 
mywords = bigstring.split() 
def FindIndexOfWord(all_words, target): 
    index = mywords[target] 
    for target in range(0, len(mywords)): 
     if target == mywords: 
      return(index) 
    return(-1) 
print(FindIndexOfWord(mywords, "have")) 

でない場合1)私は私のミスは4行目にあるかなり確信している...しかし、私は、リスト内の単語の位置を返す方法を知りません。あなたの助けが大いに評価されるでしょう!

+1

試してみます。 –

+2

参照:[list.index()](https://docs.python.org/2/tutorial/datastructures.html) –

+0

リスト内の値をインデックスまたはその値で検索しますか?達成しようとしていることに応じて、別の方法を使用する必要があります。 –

答えて

0

あなたは小さな間違いをしています。あなたは

index = mywords[target] 

を使用して文字列が他に見つかった場合、ループで使用する変数を返すことはできませんので

bigstring = "I have trouble doing this assignment" 
mywords = bigstring.split() 
def FindIndexOfWord(all_words, target): 
    for i in range(len(mywords)): 
     if target == all_words[i]: 
      return i 
    return -1 
print(FindIndexOfWord(mywords, "this")) 

対象が文字列ではなく整数-1

:ここ は正しいコードです
+0

それはこのようにもっと意味があります! – Alek

+0

upvoteもしあなたの問題を解決したら。お力になれて、嬉しいです。 –

1

文字列に.find(word)を使用すると、単語のインデックスを取得できます。

+0

私は彼が許可されていないと思う、それはコーディング(ループやもの)を練習する宿題です。 – Maroun

+0

私はそうすることができれば、正確にはこれらの方法を使用しません... – Alek

0

連想リスト使用中.index()機能を単語のインデックスを見つけて、安全のためにある単語を下に使用exception.Shownが見つからない場合、あなたのコードを終了:

bigstring = "I have trouble doing this assignment" 
mywords = bigstring.split() 
def FindIndexOfWord(list,word): 
    try: 
     print(list.index(word)) 
    except ValueError: 
     print(word," not in list.") 

FindIndexOfWord(mywords,"have") 

出力: `それはやっているかを確認するためのループ内の印刷(ターゲット)`追加

1 
関連する問題