查看列表是否存在于另一个列表中?(Seeing if a list exists within another list?)

编程入门 行业动态 更新时间:2024-10-25 17:15:03
查看列表是否存在于另一个列表中?(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.

更多推荐

本文发布于:2023-08-06 22:24:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1457649.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:是否存在   列表   列表中   exists   list

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!