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

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

    So here's your list of words, with the potato example:

    >>> y = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY POTATO"
    >>> words = y.split()
    >>> print([words.index(s)+1 for s in words])
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 3, 9, 6, 7, 8, 4, 5, 18]
    

    The reason it prints '18' is that the word "potato" hasn't appeared before, and there are 18 items in the list of words:

    >>> for word_number, word in enumerate(words):
    ...     print(word_number+1, word)
    ...
    1 ASK
    2 NOT
    3 WHAT
    4 YOUR
    5 COUNTRY
    6 CAN
    7 DO
    8 FOR
    9 YOU
    10 ASK
    11 WHAT
    12 YOU
    13 CAN
    14 DO
    15 FOR
    16 YOUR
    17 COUNTRY
    18 POTATO
    

    index() returns the first time it finds that item in the list. Potato wasn't in the sentence previously, so the last index is returned, which is 17+1.

提交回复
热议问题