我的计划的目的是告诉用户他输入的单词的位置在哪里,例如,问你的国家可以做什么,因为你问你可以为你的国家做什么 “国家”一词出现在第5和第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)
答案 0 :(得分:0)
试试这个......
第一次出现在x 中的第一次出现的 s.index(x)
- 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;
答案 1 :(得分:0)
在索引中,您需要指定开始搜索的起始索引,否则它将始终返回第一个匹配的索引。
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
答案 2 :(得分:0)
这是一个与您的输入和预期输出(第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)
答案 3 :(得分:0)
这是for loop
for x in range(len(Sentence)):
if Sentence[x]==findword:
Position = x
print(Position)
答案 4 :(得分:0)
试试这段代码 -
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()