See if a list exists in another list?

In principle, I will say that I have:

>>> a = [1,3,2,2,2]
>>> b = [1,3,2]

I want to see if all elements from b exist within a and in the same order. So, for the above example, b will exist within.

I really hope this is a really simple one line answer.

+3
source share
6 answers

This is a simple O (n * m) algorithm:

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

Please note that this is not the fastest way to do this. If you need high performance, you can use similar methods for those used in string search algorithms .

+6
source

' ' ( ), -- :

  def is_subsequence(x, y):
    i, j = 0, 0
    while i < len(x) and j < len(y):
      if x[i] == y[j]:
        i += 1
      j += 1
    return i == len(x)
+2

, ints.

, , [1, 3, 2] "1", "3", "2". , , .

repr(map(str, b))[1:-1] in repr(map(str, a))[1:-1]
+1

, , , :

In [1]: a = [1,3,2,2,2]

In [2]: b = [1,3,2]

In [3]: b == [val for val in a if val in b]
Out[3]: False

In [4]: a = [6,1,3,2,5,4]

In [5]: b == [val for val in a if val in b]
Out[5]: True

False - 2. , . , a:

In [6]: a = [1,3,2,2,2]

In [7]: b == [val for val in a if val in b][:len(b)]
Out[7]: True
0

, , , ( ). , Knuth-Morris-Pratt Boyer Moore .

:
, " " . , , .

0

" ",

>>> a = [1,3,2,2,2]
>>> b = [1,3,2]
>>> ' '.join(map(str,b)) in ' '.join(map(str,a))
True

>>> a = [1,1,2,2,2,13,2]
>>> b = [1,3,2]
>>> ' '.join(map(str,b)) in ' '.join(map(str,a))
False
-2

Source: https://habr.com/ru/post/1733753/


All Articles