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

如何用if语句检查嵌套列表中指定单词后是否紧跟'is'?

解决方案

针对你的需求,完全可以用if语句实现精准筛选,下面是两种可行的方法:

方法1:检查单词相邻关系(通用场景)

把句子拆分成单词列表,遍历检查是否存在**前一个单词属于word_list、当前单词是is**的情况:

List1 = [["Red is my favorite color."],["Blue is her favorite."], ["She is really nice."]]
word_list = ['Red', 'Blue']
target_sentences = []

# 遍历嵌套列表中的每个子列表
for item in List1:
    sentence = item[0]
    words = sentence.split()  # 按空格拆分句子为单词
    # 从第二个单词开始,检查前一个单词是否符合要求
    for idx in range(1, len(words)):
        if words[idx] == 'is' and words[idx-1] in word_list:
            target_sentences.append(item)
            break  # 找到符合条件的就停止当前句子的检查

print(target_sentences)

运行结果会返回你需要的前两个句子:[['Red is my favorite color.'], ['Blue is her favorite.']]

方法2:字符串直接匹配(规整格式场景)

如果你的句子格式很规整(目标单词和is之间只有单个空格,没有标点附着),可以直接检查{单词} is是否存在于句子中:

List1 = [["Red is my favorite color."],["Blue is her favorite."], ["She is really nice."]]
word_list = ['Red', 'Blue']
target_sentences = []

for item in List1:
    sentence = item[0]
    # 遍历目标单词列表,检查是否有匹配的短语
    for word in word_list:
        if f"{word} is" in sentence:
            target_sentences.append(item)
            break

print(target_sentences)

这个方法代码更简洁,适合句子格式固定的场景。

原方法的问题

你之前用if 'is' in sentences的逻辑,只是判断句子中是否包含is,完全不关心它的前置单词,所以会把第三个包含is的句子也筛选出来。上面两种方法都是针对性检查is的前置词是否在指定列表中,因此能精准过滤出符合要求的句子。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 07:48:27