如何判断list_2的元素是否按原顺序存在于list_1中?
判断列表是否为另一列表的顺序一致子序列
需求说明
给定三个列表:
- list_1:
['one', 'took', 'a', 'walk', 'yeah', 'i', 'watched', 'the', 'world', 'happens', 'now'] - list_2:
['yeah', 'i', 'watched', 'the', 'world'] - list_3:
['yeah', 'one', 'took', 'a', 'world', 'walk', 'i', 'the', 'happens', 'now', 'watched']
需要实现逻辑:判断list_2的元素是否按相同顺序出现在目标列表中(无需连续,不关心起始和结束位置)。预期结果:
- list_1与list_2对比返回
True - list_3与list_2对比返回
False
实现代码
可以通过遍历主列表,逐个匹配子列表元素的方式实现:
def is_subsequence(sub_list, main_list): sub_idx = 0 for item in main_list: if sub_idx < len(sub_list) and item == sub_list[sub_idx]: sub_idx += 1 return sub_idx == len(sub_list) # 测试案例 list_1 = ['one', 'took', 'a', 'walk', 'yeah', 'i', 'watched', 'the', 'world', 'happens', 'now'] list_2 = ['yeah', 'i', 'watched', 'the', 'world'] list_3 = ['yeah', 'one', 'took', 'a', 'world', 'walk', 'i', 'the', 'happens', 'now', 'watched'] print(is_subsequence(list_2, list_1)) # 输出: True print(is_subsequence(list_2, list_3)) # 输出: False
代码逻辑说明
- 初始化子列表的索引
sub_idx为0,用于追踪当前需要匹配的子列表元素 - 遍历主列表的每个元素:
- 如果当前子列表索引未超出范围,且主列表元素与子列表当前索引元素匹配,则子列表索引加1
- 遍历结束后,若子列表索引等于子列表长度,说明所有元素按顺序匹配完成,返回
True;否则返回False
内容的提问来源于stack exchange,提问作者user20716077
相关产品推荐
相关产品推荐

