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

Python实现:检查列表中连续两词是否存在于另一列表并提取

检查列表中连续元素是否同时存在于另一列表的Python实现

这个需求其实挺常见的,核心就是要遍历目标列表里的连续元素对,再验证它们是否都在参考列表中。下面给你几个实用的实现方案,从基础易读到简洁紧凑都有:

基础遍历版(易读性拉满)

先把参考列表b转成集合——这步很关键,因为集合的成员检查速度比列表快得多,数据量大的时候能明显提升效率。然后逐个检查a里的连续元素对:

a = ['The', 'man', 'is', 'eating', 'pear']
b = ['these', 'are', 'random', 'words', 'but', 'they', 'have', 'pear', 'and', 'eating']

# 转换为集合优化查找性能
b_set = set(b)
c = []

# 遍历a中的连续元素对(索引从0到倒数第二个元素,避免越界)
for i in range(len(a) - 1):
    current_element = a[i]
    next_element = a[i + 1]
    # 检查两个元素是否都在b的集合中
    if current_element in b_set and next_element in b_set:
        c = [current_element, next_element]
        # 找到第一组匹配的就退出循环,完全符合题目需求
        break

print(c)  # 输出: ['eating', 'pear']

简洁生成器版(代码更紧凑)

如果想让代码更精简,可以用生成器表达式配合next()函数,一行就能搞定查找逻辑:

a = ['The', 'man', 'is', 'eating', 'pear']
b = ['these', 'are', 'random', 'words', 'but', 'they', 'have', 'pear', 'and', 'eating']
b_set = set(b)

# 生成器遍历所有可能的连续对,next()取第一个匹配的,默认返回空列表
c = next(([a[i], a[i+1]] for i in range(len(a)-1) if a[i] in b_set and a[i+1] in b_set), [])

print(c)  # 输出: ['eating', 'pear']

拓展:找到所有符合条件的连续对

如果你的需求不只是找第一组,而是要把所有符合条件的连续元素对都找出来,用列表推导式就能轻松实现:

a = ['The', 'man', 'is', 'eating', 'pear', 'apple', 'eating']
b = ['these', 'are', 'random', 'words', 'but', 'they', 'have', 'pear', 'and', 'eating', 'apple']
b_set = set(b)

# 收集所有符合条件的连续对
all_matching_pairs = [[a[i], a[i+1]] for i in range(len(a)-1) if a[i] in b_set and a[i+1] in b_set]

print(all_matching_pairs)  # 输出: [['eating', 'pear'], ['pear', 'apple'], ['apple', 'eating']]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:28:25