在保留列表顺序的同时检查一个列表是否为另一个列表的一部分 [英] Check if a list is part of another list while preserving the list sequence

查看:51
本文介绍了在保留列表顺序的同时检查一个列表是否为另一个列表的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在保留顺序的情况下检查python中的列表是否为另一个列表的一部分.示例:

How to check if a list in python is part of another list with preserving the order. Example:

a = [3, 4, 1, 2, 5]
b = [4, 1, 2]
Answer is True

a = [3, 4, 1, 0, 2, 5]
b = [4, 1, 2]
Answer is False as the order is not matched

推荐答案

这可以使用 python 列表相等来解决,比较所有位置的子列表:

This can be solved using python lists equality, comparing the sublists at all positions:

is_b_sublist_of_a = any(b == a[i:i+len(b)] for i in range(len(a)))

表达式 a [i:i + len(b)] 从第 i 个开始创建一个长度为 b 的列表位置.此表达式是针对 a 中的所有位置计算的.如果任何比较返回 True ,则 any 表达式也将为 True ,否则为 False .

The expression a[i:i+len(b)] creates a list at the length of b starting from the ith position. This expression is computed for all positions in a. If any of the comparisons return True, the any expression will be True as well, and False otherwise.

这篇关于在保留列表顺序的同时检查一个列表是否为另一个列表的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆