在列表中查找单词

时间:2016-02-02 11:18:07

标签: python python-3.x

我正在尝试制作能够找到某个单词在列表中的位置的内容,然后告诉您它到底在哪里是我目前所拥有的:

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

3 个答案:

答案 0 :(得分:1)

whenAppears += 1放在if块之后。将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使你的代码更好,但这些是你必须解决的错误。

答案 1 :(得分:0)

您以不正确的方式使用循环。 您必须将wordelword进行比较,因为只要您循环phrase,该值就会存储在word中。

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

答案 2 :(得分: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))