在列表中使用.index时,仅在第一次出现在数组中时返回

时间:2015-11-17 09:22:49

标签: python list python-3.x

sentence = "ask not what your country can do for you ask what you can do for your country"
sentList = sentence.split()

print(sentence)
userWord = input("Pick a word from the sentence above").lower()

if userWord in sentList:

    while True:
       if sentList.index(userWord) + 1 >= 4:
          print (userWord, "appears in the sentence in the",sentList.index(userWord) + 1,"th position")
          break

    elif sentList.index(userWord) + 1 == 3:
          print (userWord, "appears in the sentence in the",sentList.index(userWord) + 1,"rd position")
          break

    elif sentList.index(userWord) + 1 == 2:
        print (userWord, "appears in the sentence in the",sentList.index(userWord) + 1,"nd position")
        break

    elif sentList.index(userWord) + 1 == 1:
         print (userWord, "appears in the sentence in the",sentList.index(userWord) + 1,"st position")
         break

else:
     userWord = input("That word isn't in the sentence, try again")

当我运行程序时,它只返回它第一次出现在数组中的位置。

即     不要问你的国家可以为你做什么,问你可以为你的国家做些什么

从上面的句子中选择一个单词:ask

'ask'出现在第一位的句子中

为什么会发生这种情况,我该如何解决?

很抱歉,如果这是一个愚蠢的问题我是编码noobie

2 个答案:

答案 0 :(得分:1)

list.index接受额外的起始索引(和结束索引)。传递索引以查找下一个匹配的项目索引。

...

if userWord in sentList:
    i = 0
    while True:
        try:
            i = sentList.index(userWord, i)  # <---
        except ValueError:  # will raise ValueError unless the item is found
            break
        i += 1
        print("{} appears in the sentence in the {}th position".format(
            userWord, i
        ))

else:
     ....

答案 1 :(得分:1)

另一个答案更好。 我把这个作为另一种方式的例子。

根据https://docs.python.org/3.3/tutorial/datastructures.html

的python文档
Index: Return the index in the list of the first item whose value is x. It is an error if there is no such item.

你应该使用for循环(最简单的方法),或者它可能是编写生成器的一个很好的例子。

for i,word in enumerate(sentList):
    if userWord == word:
        checkLocation(i,userWord)

def checkLocation(index,userWord):
    if index + 1 >= 4:
        print (userWord, "appears in the sentence in the",index + 1,"th position")
    elif 
        index + 1 == 3:
        print (userWord, "appears in the sentence in the",index + 1,"rd position")
    elif 
        index + 1 == 2:
        print (userWord, "appears in the sentence in the",index + 1,"nd position")
    elif 
        index + 1 == 1:
        print (userWord, "appears in the sentence in the",index + 1,"st position")