2017-12-27 411 views
-1

我一直在试图做一个函数,可以采取两个任何大小的列表(比如说,列表A和列表B),并看到列表B是否出现在列表中A,但是连续且以相同的顺序。如果以上情况属实,则返回True,否则返回False。蟒蛇 - 比较两个列表,看看是否发生在另一个连续

例如,

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 

我试着这样做使用嵌套循环到目前为止并感到有点困惑,去哪里

+1

可能要看一看的https:/ /stackoverflow.com/questions/10106901/elegant-find-sub-list-in-list –

+0

这是你所需要的: https://stackoverflow.com/questions/16579085/python-verifying-if-one-list-is-a-subset-of-the-other –

回答

0

就试试这个:

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的长度相同。如果是的话,那么你知道这个说法是正确的!

+0

谢谢。我正在尝试一些与标题一起的东西,但无法将我的头包裹在索引应该是什么。 –

+0

没问题,如果这个工程,然后请接受答案:) –

0

我转换的整个列表变成一个字符串,然后发现字符串的一个子

列表时转换成一个字符串变得

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' 

现在的问题只是转换为

检查是否有在字符串的子 所以我们可以我们在运营商检查子

解决方案

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

0

如果你的数组不是巨大的,如果你能找到一种方法,你的数组到一个字符串中的每个元素映射你可以使用:

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' 

它只是提出两个字符串从列表,比使用'在' 找到任何accorence

0

使用任何功能

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

demo

0

试试这个:

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 
0

您可以创建一个可分析的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}