You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在列表的句子元素中查找指定单词所在的列表索引

解决方法:在句子列表中查找包含目标单词的元素索引

Hey there! I get what you're asking—since your list has full sentences instead of single words, the index() method (which looks for exact matches of the entire element) won't work directly. Let's fix that with a couple straightforward approaches:

方法1:简洁的列表推导式(基础匹配)

Using enumerate() is perfect here because it lets you loop through both the index and value of each element in your list at the same time. We'll check if the target word is present in each sentence, and collect the indices where it's found:

# 定义你的列表
my_list = ['i like python', 'i dont like to do anything else', 'python is fun', 'i like to bowl']
target_word = 'python'

# 用列表推导式收集符合条件的索引
matching_indices = [idx for idx, sentence in enumerate(my_list) if target_word in sentence]

print(matching_indices)  # 输出: [0, 2]

代码解释:

  • enumerate(my_list) 返回类似 (0, 'i like python')、(1, 'i dont like...') 的配对,这样我们能同时拿到元素的位置(idx)和句子内容。
  • 条件 target_word in sentence 用于检查目标单词是否出现在当前句子中。
  • 我们只保留条件成立时对应的idx值。

方法2:精确匹配整个单词(避免部分匹配)

如果你想确保匹配的是完整单词(比如不想把包含'pythonic'的句子也算进去),可以先把句子拆分成单个单词再检查:

matching_indices = [idx for idx, sentence in enumerate(my_list) if target_word in sentence.split()]

sentence.split() 会把句子按空格拆分成单词列表,target_word in sentence.split() 就能检查目标单词是否作为独立条目存在于这个列表中。

对比你熟悉的index()方法

这里再明确下为什么index()不适用:words.index('hello')是在列表中找完全等于'hello'的元素。而你的场景里,列表元素是完整句子,需要检查元素内部是否包含目标单词,而不是匹配整个元素本身。

内容的提问来源于stack exchange,提问作者Dylancam909

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:03:59