gpt4 book ai didi

python - 在列表中使用 .index 时,仅返回它第一次出现在数组中的时间

转载 作者:行者123 更新时间:2023-12-01 04:20:37 24 4
gpt4 key购买 nike

sentence = "ask not what your country can do for you ask what you can do for your country"
sentList = sentence.split()

print(sentence)
userWord = input("Pick a word from the sentence above").lower()

if userWord in sentList:

while True:
if sentList.index(userWord) + 1 >= 4:
print (userWord, "appears in the sentence in the",sentList.index(userWord) + 1,"th position")
break

elif sentList.index(userWord) + 1 == 3:
print (userWord, "appears in the sentence in the",sentList.index(userWord) + 1,"rd position")
break

elif sentList.index(userWord) + 1 == 2:
print (userWord, "appears in the sentence in the",sentList.index(userWord) + 1,"nd position")
break

elif sentList.index(userWord) + 1 == 1:
print (userWord, "appears in the sentence in the",sentList.index(userWord) + 1,"st position")
break

else:
userWord = input("That word isn't in the sentence, try again")

当我运行程序时,它只返回它第一次出现在数组中的位置。

即 不要问你的国家能为你做什么,而要问你能为你的国家做什么

从上面的句子中选择一个词:问

“ask”出现在句子中的第一个位置

为什么会发生这种情况以及如何解决它?

抱歉,如果这是一个愚蠢的问题,我是一个编码新手

最佳答案

另一个答案更好。我将此作为另一种方法的示例。

根据Python文档https://docs.python.org/3.3/tutorial/datastructures.html

Index: Return the index in the list of the first item whose value is x. It is an error if there is no such item.

您可能应该使用 for 循环(最简单的方法),或者它可能是编写生成器的一个很好的示例。

for i,word in enumerate(sentList):
if userWord == word:
checkLocation(i,userWord)

def checkLocation(index,userWord):
if index + 1 >= 4:
print (userWord, "appears in the sentence in the",index + 1,"th position")
elif
index + 1 == 3:
print (userWord, "appears in the sentence in the",index + 1,"rd position")
elif
index + 1 == 2:
print (userWord, "appears in the sentence in the",index + 1,"nd position")
elif
index + 1 == 1:
print (userWord, "appears in the sentence in the",index + 1,"st position")

关于python - 在列表中使用 .index 时,仅返回它第一次出现在数组中的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33753194/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com