【问题标题】:How to check if a list is in another list with the same order python [duplicate]如何检查一个列表是否在另一个具有相同顺序的列表中python [重复]
【发布时间】:2016-03-15 15:54:48
【问题描述】:

我的问题与典型问题不同。假设我们有,

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

谁能给我任何想法?

【问题讨论】:

    标签: python list


    【解决方案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
    

    【讨论】:

      【解决方案2】:
      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
      

      【讨论】:

        【解决方案3】:

        如果您的号码始终为三位数,一种可能的解决方案:

        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
        

        【讨论】:

          猜你喜欢
          • 2012-06-26
          • 1970-01-01
          • 1970-01-01
          • 2014-04-24
          • 1970-01-01
          • 2023-03-22
          • 1970-01-01
          • 1970-01-01
          • 2021-10-06
          相关资源
          最近更新 更多