When using .index in a list only returns first time it appears in the array

前端 未结 2 1306
[愿得一人]
[愿得一人] 2021-01-23 16:12
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          


        
相关标签:
2条回答
  • 2021-01-23 16:27

    list.index accepts additional start index (and end index). Pass the index to find next matched item 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:
         ....
    
    0 讨论(0)
  • 2021-01-23 16:33

    The other answer is better. I left this one as an example of an alternative way.

    according to the python documentation at https://docs.python.org/3.3/tutorial/datastructures.html

    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.
    

    you should probably use a for loop (the easiest way) or probably it will be a good example of writing a generator.

    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")
    
    0 讨论(0)
提交回复
热议问题