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

前端 未结 3 1049
栀梦
栀梦 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:18

    In your sentence, the list becomes:

    ['ASK', 'NOT', 'WHAT', 'YOUR', 'COUNTRY', 'CAN', 'DO', 'FOR', 'YOU', 'ASK', 'WHAT', 'YOU', 'CAN', 'DO', 'FOR', 'YOUR', 'COUNTRY', 'POTATO']
    

    POTATO is the 18th element. You should create a new list with no duplicates:

    singles = []
    for word in words:
        if word not in singles:
            singles.append(word)
    

    You can then use singles.index(word) instead of words.index(word). Even better:

    used = {}
    index = 0
    for word in words:
        if word in used:
            print(used[word])
        else:
            index += 1
            print(index)
            used[word] = index
    

    Yes, it's longer, but it is more efficient.

提交回复
热议问题