簡體   English   中英

我如何檢查一個列表是否以相同的順序在另一個列表中?

[英]How would I check if a list is in another list in the same order?

基本上,對於一項作業,我需要確定一個列表是否是另一個列表的子列表,我在這篇文章Checking if list is a sublist 中得到了回答,但是有一些特殊要求,將在示例中解釋,但沒有在那個帖子里回答了。 我還看到了這篇文章How to check if a list is in another list with the same order python這也沒有幫助確定特殊要求。

示例 1:

list1 = 'a,q,b,q,q,q,q,q,q,c'
sublist = 'a,b,c'
output -> True

解釋:現在,我知道這不一定是 list1 的子列表,但是 a、b 和 c 都出現在 list1 中,與子列表變量的順序相同,只有 q 將它們分開,我可以忽略它,因為 q不在子列表中,這就是為什么這會輸出 true。

示例2:

list1 = 'b,q,q,q,q,a,q,c'
sublist = 'a,b,c'
output -> False

說明:雖然這個列表確實像另一個例子一樣包含 a、b 和 c,但它是亂序的,因此為什么它會是假的

示例3:

list1 = 'a,b,b,q,c'
sublist = 'a,b,c'
output -> False

示例 4:

list1 = 'a,b,b,a,b,q,c'
sublist = 'a,b,c'
output -> True

說明:在列表的開頭我們有 a,b,b,在我之前的解釋中我說是錯誤的,但是在該部分之后我們有正確的 a,b,c 順序,用 aq 分隔 b 和 c

這是我的代碼。 我似乎無法找到的問題出現在我必須運行的一個隱藏測試用例中,我看不到輸入或輸出,這使得調試變得困難。 我已經嘗試運行許多我自己的不同測試用例,但我似乎無法在這里找到我缺少的東西。 我只是想知道是否有人能弄清楚我在運行時忘記考慮什么。

sublist = 'a,b,c'.split(',')
l1 = 'a,q,b,a,q,q,q,q,q,q,q,q,q,c'.split(',')
item_order = []

for item in l1:
    #Check if I have found a sublist
    if item_order == sublist:
        break

    #If item is in sublist, but hasnt been seen yet
    elif item in sublist and item not in item_order:
        item_order.append(item)
        print('adding item', item_order)

    #If item has been seen and is in sublist
    elif item in item_order:
        #Reset and add duplicated item 
        item_order = []
        item_order.append(item)
        print('found duplicate, resetting list', item_order)

if item_order == sublist: print("true")
else: print("false")

您可以過濾list1中不存在於sublist的元素並將其與sublist進行比較,即:

def good_seq(list1, sublist):
    return [x for x in list1.split(",") if x in sublist.split(",")] == sublist.split(",")

演示

您可以嘗試以下操作:

def dedupe(items):
    """Function to remove duplicate by preserving its order

    Args:
        items (list): the list  for which the duplicates must be removed

    Yields:
        generator: the generator with unique items
    """
    seen = set()
    for item in items:
        if item not in seen:
            yield item
            seen.add(item)

def check_order(l1, sublist):
    l1 = list(dedupe(l1))
    result = [val for val in l1 if val in sublist] == sublist
    return result

sublist = 'a,b,c'.split(',')
l1 = 'a,q,b,a,q,q,q,q,q,q,q,q,q,c'.split(',')
print(check_order(l1, sublist))

sublist = 'a,b,c'.split(',')
l1 = 'b,q,q,q,q,a,q,c'.split(',')
print(check_order(l1, sublist))

輸出:

True
False

暫無
暫無

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

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