Skip to main content
 首页 » 编程设计

python之从输入中获取列表中项目的位置 (Python)

2024年10月24日18lautakyan007

我有一个包含单词的列表。我想获得单词在用户要求的句子中的位置。 (我正在使用 python ) 例如,如果我有以下句子:"Hello world you doing how are you doing today world?" 'World' 出现在第一和第八位置。如果用户想知道单词 'world' 在该句子中的位置,它会打印 “The word world is in position 1 and 8”。我知道 enumerate 方法,但无法让它与输入或 elif 语句一起使用。我想获得句子中任何单词的位置,无论该单词出现多少次。

请您参考如下方法:

sentence = "Hello world how are you doing today world?".lower() 
searchword = input("Enter word:  ").lower() 
 
newsentence = '' 
 
for character in sentence: 
    if character.islower() or character == ' ': newsentence += character 
 
answer = [position for position, word in enumerate(newsentence.split()) if searchword == word] 
 
print(answer)