且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在保留列表顺序的同时检查一个列表是否为另一个列表的一部分

更新时间:2023-11-25 23:09:04

这可以使用 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.