如何检查列表是否在具有相同订单python的另一个列表中

时间:2016-03-15 15:54:49

标签: 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']
# should return False since elements in C are not adjacent in X

任何人都可以给我任何想法吗?

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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

答案 2 :(得分:-1)

如果您的号码总是三位数,则可以采用一种解决方法:

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