2016-02-02 74 views
0

我试图使一些发现,其中一个字是在列表中,然后告诉你在哪儿。这是我到目前为止有:查找单词在列表

whenAppears = 0 
when = [] 
i = 0 
phrase = str(input("What sentence? ")) 
phrase = phrase.lower() 
phrase = phrase.split() 
print(phrase) 
wordel = str(input("What single word would you like to find? ")) 
wordel = wordel.lower() 
if wordel in phrase: 
    print ("That word is in the phrase, there are",phrase.count(wordel),wordel+"('s)""in the sentence") 
for word in phrase: 
    whenAppears += 1 
    if wordel == phrase[i]: 
     when.append(whenAppears) 
print ("The word",wordel,"is in the slot",when) 

不管我把它说这个词是在插槽1和任何其他插槽,我不能想到任何方式来这个,请帮助:D

+0

看看在['list.index'](https://docs.python.org/3/library/stdtypes.html #common-sequence-operations)方法来更有效地找到项目列表中项目的位置。 –

回答

1

whenAppears += 1if块之后。将wordel == phrase[i]更改为wordel == word。删除行i = 0

更正代码:

whenAppears = 0 
when = [] 
phrase = str(input("What sentence? ")) 
phrase = phrase.lower() 
phrase = phrase.split() 
print(phrase) 
wordel = str(input("What single word would you like to find? ")) 
wordel = wordel.lower() 
if wordel in phrase: 
    print ("That word is in the phrase, there are",phrase.count(wordel),wordel+"('s)""in the sentence") 
for word in phrase: 
    if wordel == word: 
     when.append(whenAppears) 
    whenAppears += 1 
print ("The word",wordel,"is in the slot",when) 

你可以让你的代码内涵和enumerate更好,但这些都是你一定要修复错误。

+0

非常感谢:DDDDDD !! – Harry

0

您以不正确的方式使用循环。 您必须将wordelword进行比较,因为任何时候循环使用phrase时,该值都将存储在word中。

for word in phrase: 
    whenAppears += 1 
    if wordel == word: 
     when.append(whenAppears) 
0

您可以用list.index更有效地重写代码:

phrase = str(input("What sentence? ")).lower().split() 
print(phrase) 
wordel = str(input("What single word would you like to find? ")).lower() 
if wordel in phrase: 
    print ("That word is in the phrase, there are",phrase.count(wordel), wordel+"('s)""in the sentence") 
    print ("The word",wordel,"is in the slot", phrase.index(wordel))