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

标签 python list python-3.x

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/

相关文章:

python - 使用 Pandas 复制非 na 行以填充非 na 列

python - 在Python中通过正则表达式优化在两个列表之间查找匹配子字符串

java - 将逗号与列表分开并在Java中显示在单行中

java - 将 Arrays.asList 与 int 数组一起使用

python-3.x - distutils include_dirs 与相对路径?

python - 如果函数抛出异常则不返回是不好的做法吗?

python - 使用特定键的顺序对字典列表进行排序

python - Numpy append 不允许串联

Python sqlite3 库无法使用 URI,即使 sqlite3 版本应该能够

python-3.x - Python退出代码