Why does my code print off 18 instead of 10, and could you provide any solutions?

前端 未结 3 1173
栀梦
栀梦 2021-01-16 05:39

I\'m relatively new to python, just started learning at school at we\'ve been given a task to complete, it asks for you to get a sentence and turn it into a list of words.

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-16 06:13

    The problem

    You're expecting your code to give you the index of the word without counting repeated words, but you're getting simply the word index in your original string.

    The solution

    First you need to get the unique words in the original string, so that you get the right word index as per your needs. You can try a demo here. With the Potato extra word, it returns the index 10 instead of 18, since it looks for it in the unique list, instead of the original one.

    string = 'ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY POTATO'
    words = string.split()
    unique_words = []
    
    #Remove the duplicates while preserving order
    for word in words:
        if word not in unique_words:
            unique_words.append(word)
            
    #Generate the indexes for the words
    indexes = [unique_words.index(word)+1 for word in words]
    print(indexes)
    #[1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 3, 9, 6, 7, 8, 4, 5, 10]
    

提交回复
热议问题