查看列表是否存在于另一个列表中?(Seeing if a list exists within another list?)
基本上我可以说:
>>> a = [1,3,2,2,2] >>> b = [1,3,2]我想看看b中的所有元素是否存在于a和同一顺序中。 因此,对于上面的例子,b将存在于a中。
我有点希望这是一个非常简单的答案。
Basically lets say i have:
>>> a = [1,3,2,2,2] >>> b = [1,3,2]I want to see if the all the elements in b, exists within a, and in the same order. So for the above example b would exist within a.
I am kinda hoping theres a really simple one line answer.
最满意答案
这是一个简单的O(n * m)算法:
any(a[i:i + len(b)] == b for i in range(len(a) - len(b) + 1))请注意,这不是最快的方法。 如果您需要高性能,则可以使用与字符串搜索算法中使用的技术类似的技术。
This is a simple O(n * m) algorithm:
any(a[i:i + len(b)] == b for i in range(len(a) - len(b) + 1))Note that is not the fastest way of doing this. If you need high performance you could use similar techniques to those used in string searching algorithms.
更多推荐
发布评论