如何获得两个答案



我的程序的重点是告诉用户他输入的单词的位置在哪里,例如,不问您的国家可以为您做什么,问您可以为您的国家做什么"国家"一词出现在第五和第17位。

我的程序仅两次打印第一个位置。我希望我能得到一些帮助。

 Sentence = "the quick brown fox jumped over the lazy dog"
print (Sentence)
Sentence = Sentence.split()
while True:
    findword = input("Please enter the word to find: ")
    if not findword.isalpha() or len (findword)<3:
        print("Invalid") 
    break
for x in Sentence:
    if x==findword:
        Position = Sentence.index(findword)
        print(Position)

这是一个与您的输入和预期输出(第5和17位(匹配的解决方案

Sentence = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY"
print(Sentence)
Sentence = Sentence.split()
while True:
    findword = input("Please enter the word to find: ")
    if not findword.isalpha() or len(findword) < 3:
        print("Invalid")
    break
curr_position = 0
for x in Sentence:
    if x == findword:
        Position = Sentence.index(findword, curr_position + 1)
        curr_position = Position
        print(Position + 1)

在索引中您需要指定启动索引以启动搜索,否则它将始终返回第一个匹配的索引。

prevPosition = 0
for x in Sentence:
    if x==findword:
        Position = Sentence.index(findword, prevPosition)
        prevPosition = Position + 1
        print(Position)

示例:

>>> Sentence
['the', 'quick', 'brown', 'fox', 'jumped', 'over', 'the', 'lazy', 'dog']
>>> findword = "the"
>>> prevPosition = 0
>>> 
>>> for x in Sentence:
...     if x==findword:
...         Position = Sentence.index(findword, prevPosition)
...         prevPosition = Position + 1
...         print(Position)
... 
0
6

这是for loop

的更改
for x in range(len(Sentence)):
    if Sentence[x]==findword:
        Position = x
        print(Position)

尝试此代码 -

Sentence = "the quick brown fox jumped over the lazy dog"
Sentence = Sentence.split()
print (Sentence)
findword = input("Please enter the word to find: ")
if not findword.isalpha() or len (findword)<3:
    print("Invalid") 
for wordIndex, x in enumerate(Sentence):
    if x == findword:
        print(wordIndex)

输入过程中卸下while True循环。无论如何,您都在第一次迭代后打破。循环使用时,enumerate()将返回该元素的索引以及元素。这样您就可以忘记致电index()

尝试这个...

s.index(x) -s

中第一次出现的index
Sentence = "the quick brown fox jumped over the lazy dog"
print (Sentence)
Sentence = Sentence.split()
i=0
while True:
    findword = input("Please enter the word to find: ")
    if not findword.isalpha() or len (findword)<3:
        print("Invalid") 
    break
for x in Sentence:
    if x==findword:
        Position = Sentence.index(findword, i)
        print(Position)
    i=i+1;

最新更新