Python 如何检查一个列表是否在另一个具有相同顺序的列表中
我的问题与典型的不同。假设我们有Python 如何检查一个列表是否在另一个具有相同顺序的列表中,python,list,Python,List,我的问题与典型的不同。假设我们有 X = ['123', '456', '789'] 我们想知道另一个列表是否在X中,顺序完全相同。比如说, A = ['123', '456'] # should return True since A in X with same order B = ['456', '123'] # should return False since elements in B are not in same order with X C = ['123', '789']
X = ['123', '456', '789']
我们想知道另一个列表是否在X中,顺序完全相同。比如说,
A = ['123', '456']
# should return True since A in X with same order
B = ['456', '123']
# should return False since elements in B are not in same order with X
C = ['123', '789']
# should return False since elements in C are not adjacent in X
有人能给我一些建议吗?如果您的数字总是三位数,那么有一个可能的解决方案:
x = ['123', '456', '789']
A = ['123', '456']
''.join(A) in ''.join(x)
B = ['456', '123']
''.join(B) in ''.join(x)
C = ['123', '789']
''.join(C) in ''.join(x)
但是,容易出现错误,例如:
D = ['1', '23']
''.join(D) in ''.join(x)
outputs True
Python 2:
def is_a_in_x(A, X):
for i in xrange(len(X) - len(A) + 1):
if A == X[i:i+len(A)]: return True
return False
Python 3:
def is_a_in_x(A, X):
for i in range(len(X) - len(A) + 1):
if A == X[i:i+len(A)]: return True
return False
def foo(your_list, your_main_list):
list_len = len(your_list)
for i, item in enumerate(your_list):
if your_main_list[i] == item:
if i + 1 == list_len:
return True
else:
return False