python - 比较两个列表以查看一个列表是否连续出现在另一个列表中

python - Comparing two lists to see if one occurs in another consecutively

我一直在尝试制作一个函数,该函数可以接受两个任意大小的列表(例如,列表 A 和列表 B),并查看列表 B 是否出现在列表 A 中,但连续且顺序相同。如果以上为真,则 return 为真,否则为 return 假

例如

A:[9,0,**1,2,3,4,5,6,**7,8] and B:[1,2,3,4,5,6] is successful

A:[1,2,0,3,4,0,5,6,0] and B:[1,2,3,4,5,6] is unsuccessful.

A:[1,2,3,4,5,6] and B [6,5,3,2,1,4] fails because despite having the same 
 numbers, they aren't in the same order

到目前为止,我已经尝试使用嵌套循环来执行此操作,但对于去哪里有点困惑

我将整个列表转换成一个字符串,然后找到该字符串的一个子字符串

列表转换为字符串后变为

str(a)='[9,0,1,2,3,4,5,6,7,8]'

当我们剥离字符串时变成

str(a).strip('[]')='9,0,1,2,3,4,5,6,7,8'

现在问题刚好转换为

检查字符串中是否有子串 所以我们可以使用 in 运算符来检查子字符串

解决方法

a=[9,0,1,2,3,4,5,6,7,8]
b=[1,2,3,4,5,6]
print(str(b).strip('[]') in str(a).strip(']['))

testcase1

testcase2

如果您的数组不是很大,并且您可以找到一种方法将数组中的每个元素映射到一个字符串,您可以使用:

list1 = [9,0,1,2,3,4,5,6,7,8]
list2 = [1,2,3,4,5,6]

if ''.join(str(e) for e in list2) in ''.join(str(e) for e in list1):
    print 'true'

它只是从列表中生成两个字符串,然后使用 'in' 找到任何对应关系

使用任意函数

any(A[i:i+len(B)] == B  for i in range(len(A) - len(B) + 1))

demo

试试这个:

L1 = [9,0,1,2,3,4,5,6,7,8]
L2 = [1,2,3,4,5,6]
c = 0
w = 0
for a in range(len(L2)):
   for b in range(w+1, len(L1)):
      if L2[a] == L1[b]:
        c = c+1
        w = b
        break
      else:
        c = 0
    if c == len(L2):
       print('yes')
       break

这里检查 l2 的元素是否在 l1 中,如果是,则中断第一个循环,记住你离开的位置,l2 的下一个元素与 l1 的下一个元素相同,依此类推。

最后一部分是检查这种情况发生的次数是否与 l2 的长度一样多。如果是,那么你就知道这个说法是正确的!

试试这个:

L1 = [9,2,1,2,0,4,5,6,7,8]
L2 = [1,2,3,4,5,6]
def sameorder(L1,L2):
    for i in range(len(L1)-len(L2)+1):
        if L1[i:len(L2)+i]==L2:
            return True
    return False

您可以创建可以分析的 a 的子列表:

def is_consecutive(a, b):
   return any(all(c == d for c, d in zip(b, i)) for i in [a[e:e+len(b)] for e in range(len(a)-len(b))])

cases = [[[9, 0, 1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6]], [[1, 2, 0, 3, 4, 0, 5, 6, 0], [1, 2, 3, 4, 5, 6]], [[1, 2, 3, 4, 5, 6], [6, 5, 3, 2, 1, 4]]]
final_cases = {"case_{}".format(i):is_consecutive(*a) for i, a in enumerate(cases, start=1)}    

输出:

{'case_3': False, 'case_2': False, 'case_1': True}