我有这两个数组:
A = [1,2,3,4,5,6,7,8,9,0]
并且:
B = [4,5,6,7]
有没有一种方法可以检查B是否是A中的子列表,并且顺序完全相同?
我有这两个数组:
A = [1,2,3,4,5,6,7,8,9,0]
并且:
B = [4,5,6,7]
有没有一种方法可以检查B是否是A中的子列表,并且顺序完全相同?
issubset可以帮助你。
set(B).issubset(set(A))
例如:
>>> A= [1,2,3,4]
>>> B= [2,3]
>>> set(B).issubset(set(A))
True
编辑:错误,这个解决方案并不意味着元素的顺序!
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))
结果:
>>> is_slice_in_list(B,A)
True
>>> is_slice_in_list(C,A)
True
>>> is_slice_in_list(D,A)
False
使用切片:
for i in range(len(A) - len(B)):
if A[i:i+len(B)] == B:
return True
return False
range(len(A)-len(B)+1)
。 - alko我更喜欢使用index
来确定起始点。在这个小例子中,它比迭代解决方案更快:
def foo(A,B):
n=-1
while True:
try:
n = A.index(B[0],n+1)
except ValueError:
return False
if A[n:n+len(B)]==B:
return True
无论 B
是长的、短的、存在的还是不存在的,这个时间是相当恒定的。迭代解决方案的时间因 B
的起始位置而异。
为了使其更加健壮,我已经测试过以下内容:
A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 9, 8, 7, 6, 5, 4, 3, 2, 1]
哪个更长,且重复了值。
您可以使用scipy.linalg.hankel
在一行中创建所有子数组,然后检查您的数组是否在其中。以下是一个快速示例:
from scipy import linalg
A = [1,2,3,4,5,6,7,8,9,0]
B = [4,5,6,7]
hankel_mat = linalg.hankel(A, A[::-1][:len(B)])[:-1*len(B)+1] # Creating a matrix with a shift of 1 between rows, with len(B) columns
B in hankel_mat # Should return True if B exists in the same order inside A
import array
def Check_array(c):
count = 0
count2 = 0
a = array.array('i',[4, 11, 20, -4, -3, 11, 3, 0, 50]);
b = array.array('i', [20, -3, 0]);
for i in range(0,len(b)):
for j in range(count2,len(a)):
if a[j]==b[i]:
count = count + 1
count2 = j
break
if count == len(b):
return bool (True);
else:
return bool (False);
res = Check_array(8)
print(res)
list
转换为string
,您可以轻松验证字符串“4567”是否在字符串“1234567890”中。stringA = ''.join([str(_) for _ in A])
stringB = ''.join([str(_) for _ in B])
stringB in stringA
>>> True
穿着一行(因为更酷)
isBinA = ''.join([str(_) for _ in B]) in ''.join([str(_) for _ in A])
isBinA
>>> True
A = [45]
和 B = [4,5]
。 - LenormjuA = [1,2,3,4,5,6,7,8,9,0]
B = [4,5,6,7]
(A and B) == B
True