【问题标题】:find and display all indexes in a list based on keyword根据关键字查找并显示列表中的所有索引
【发布时间】:2016-01-31 17:33:10
【问题描述】:

我在 Python 3 中有以下代码,它查找并显示列表中搜索单词的第一个示例,即单词“now”位于位置 3,但如果该单词出现两次或列表中的更多内容,我找不到显示第二个/第三个等索引的方法。即单词“现在”出现在位置 3 和 5。

我在网上看到了一些非常复杂的版本,但想看看我是否可以让它变得非常简单。我知道 .index() 只能找到第一个索引,那么我可以使用其他方法吗?

代码:

sentence=input("Enter your sentence here: ")
sentence=sentence.lower()
words=(sentence.split())
print(words)
word_to_find=input("What word position do you want to find? ")
word_to_find=word_to_find.lower()

if word_to_find in words:
    position=words.index(word_to_find)
    print( "The word ", word_to_find, "is in position(s): ",position+1)
else:
    print("No word exists")

非常感谢

【问题讨论】:

    标签: list indexing python-3.4


    【解决方案1】:

    试试;

    positions = [ind for ind, x in enumerate(words) if x == word_to_find]

    现在positions 将成为wordsword_to_find 的所有索引的列表。

    【讨论】:

    • 这很棒。非常感谢 Praveen。我将研究这条线的实际含义。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 2021-08-07
    • 2013-01-28
    • 1970-01-01
    • 2011-10-04
    • 1970-01-01
    • 2018-08-31
    相关资源
    最近更新 更多