I have these two arrays:
A = [1,2,3,4,5,6,7,8,9,0]
And:
B = [4,5,6,7]
Is there a way to check if B is a sublist in A with the same exact order of items?
issubset should help you
set(B).issubset(set(A))
e.g.:
>>> A= [1,2,3,4]
>>> B= [2,3]
>>> set(B).issubset(set(A))
True
edit: wrong, this solution does not imply the order of the elements!
How about this:
A = [1,2,3,4,5,6,7,8,9,0]
B = [4,5,6,7]
C = [7,8,9,0]
D = [4,6,7,5]
def is_slice_in_list(s,l):
len_s = len(s) #so we don't recompute length of s on every iteration
return any(s == l[i:len_s+i] for i in xrange(len(l) - len_s+1))
Result:
>>> is_slice_in_list(B,A)
True
>>> is_slice_in_list(C,A)
True
>>> is_slice_in_list(D,A)
False
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With