当在列表中使用.index时,仅在其第一次出现在数组中时才返回 [英] When using .index in a list only returns first time it appears in the array

查看:87
本文介绍了当在列表中使用.index时,仅在其第一次出现在数组中时才返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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")

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

When I run the program it only returns the position of the first time it appears in the array.

即 不要问你的国家能为你做些什么?问你可以为你的国家做些什么

i.e ask not what your country can do for you ask what you can do for your country

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

Pick a word from the sentence above: ask

问"出现在句子的第一位置

'ask' appears in the sentence in the 1 st position

为什么会发生这种情况,我该如何解决?

Why does this happen and how can I fix it?

对不起,如果这是一个愚蠢的问题,我是一名编码noobie

Sorry if this is a stupid question I am a coding noobie

推荐答案

另一个答案更好. 我把这个作为替代方法的一个例子.

The other answer is better. I left this one as an example of an alternative way.

根据python文档,位于 https://docs.python.org/3.3/tutorial/datastructures.html

according to the python documentation at 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循环(最简单的方法),或者这可能是编写生成器的一个很好的例子.

you should probably use a for loop (the easiest way) or probably it will be a good example of writing a generator.

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")

这篇关于当在列表中使用.index时,仅在其第一次出现在数组中时才返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆