【问题标题】:How can I list a index of a certain word in a sentence within a list? i dont understand how it works如何在列表中列出句子中某个单词的索引?我不明白它是如何工作的
【发布时间】:2019-09-29 02:58:31
【问题描述】:

例如:

list = ['i like python', 'i dont like to do anything else', 'python is fun', 'i like to bowl']

如何遍历列表并找到单词“python”并打印包含它的列表的索引?

所以它会打印出来:

[0,2]

我了解,如果您有如下列表:

words = ['hello', 'goodbye', 'whatsup']

您可以通过以下方式搜索“你好”:

position = words.index('hello')
print(position)

它会返回单词的索引。 但我不知道如何在一个句子中找到一个单词

谢谢

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:
    indices = [i for i,string in enumerate(list) if "python" in string]
    

    【讨论】:

      【解决方案2】:

      使用列表理解:

      [i for i in range(len(list)) if "python" in list[i]]
      > [0, 2]
      

      这将返回包含“python”的句子的索引。但是,如果您只想在句子包含 word "python" 的情况下获取索引,则应该将句子拆分为单词。示例:

      list = ['i like python', 'ipython']
      [i for i in range(len(list)) if "python" in list[i]]
      > [0, 1]
      [i for i in range(len(list)) if "python" in list[i].split(" ")]
      > [0]
      

      【讨论】:

        猜你喜欢
        • 2021-05-17
        • 2020-09-02
        • 2020-09-12
        • 1970-01-01
        • 2021-09-28
        • 2017-12-26
        • 1970-01-01
        • 1970-01-01
        • 2021-03-30
        相关资源
        最近更新 更多