簡體   English   中英

如何檢查列表 (list_1) 是否包含與另一個列表 (list_2) 以相同順序排列的相同元素?

[英]How do I check if a list (list_1) contains the same elements located in same order of another list (list_2)?

我有 2 個列表:list_1 和 list_2。

list_1: ['one', 'took', 'a', 'walk', 'yeah', 'i', 'watched', 'the', 'world', 'happens', 'now']

我有

list_2: ['yeah', 'i', 'watched', 'the', 'world']

list_3: ['yeah', 'one', 'took', 'a', 'world', 'walk', 'i', 'the', 'happens', 'now', 'watched']

我想檢查list_2中的元素是否以相同的順序出現在list_1中,在這種情況下

['yeah', 'i', 'watched', 'the', 'world']

無論 list_1 中的起始位置和結束位置如何。

但是,當我比較 list_3 和 list_2 時,雖然 list_2 中的所有元素都出現在 list_3 中,但它們的排序不同。

在第一種情況下(list_1 vs list_2),答案為真。 在第二種情況下(list_3 vs list_2),答案為 False。

這是代碼。 如果您在函數中輸入 2 列表,該函數將檢查第二個列表中的所有元素是否都在第一個列表中,並且兩個列表中的順序相同。

list_1= ['one', 'took', 'a', 'walk', 'yeah', 'i', 'watched', 'the', 'world', 'happens', 'now']
list_2= ['yeah', 'i', 'watched', 'the', 'world']
list_3= ['yeah', 'one', 'took', 'a', 'world', 'walk', 'i', 'the', 'happens', 'now', 'watched']
def check(ref_list, check_list):
    matching=0
    for i in range(len(ref_list)):
        if check_list[0]==ref_list[i] and check_list[1]==ref_list[i+1]:
            for j in range(len(check_list)):
                if check_list[j]==ref_list[i+j]:
                    matching=1
                else:
                    matching=0
                if j==len(check_list)-1:
                    if matching==1:
                        print("checking list Matched with reference")
                        return 0
                    else:
                        print("Didn't match")
                        return 0
    if matching==0:
        print("Didn't match")
        return 0
check(list_1,list_2)

方法:
從 list1 的開頭開始
環形:
在 list1 的剩余部分中找到 list2 的單詞的位置。
如果不在 list1 中,則返回 False。

def match( list2, list1):
  i0 = 0 # start point in list1
  for i2 in range( len( list2)):
    for i1 in range( i0, len( list1)):
      if list1[i1]==list2[i2]:
        i0 = i1 # next search will start here
        break
    else:
      return False # not found
  return True # match

list1= ['one', 'took', 'a', 'walk', 'yeah', 'i', 'watched', 'the', 'world', 'happens', 'now']
list2= ['yeah', 'i', 'watched', 'the', 'world']
list3= ['yeah', 'one', 'took', 'a', 'world', 'walk', 'i', 'the', 'happens', 'now', 'watched']

match( list2, list1) # return True
match( list2, list3) # return False
 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM