Individual words in a list then printing the positions of those words

前端 未结 5 1373
逝去的感伤
逝去的感伤 2020-12-20 02:54

I need help with a program that identifies individual words in a sentence, stores these in a list and replaces each word in the original sentence with the position of that w

5条回答
  •  眼角桃花
    2020-12-20 03:28

    Like this? Just do a list-comprehension to get all the indices of all the words.

    In [77]: sentence = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY"
    
    In [78]: words = sentence.split()
    
    In [79]: [words.index(s)+1 for s in words]
    Out[79]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 3, 9, 6, 7, 8, 4, 5]
    

提交回复
热议问题