2017-12-27 410 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}