亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何按順序檢查一個列表是否是另一個列表的子序列

如何按順序檢查一個列表是否是另一個列表的子序列

慕慕森 2023-04-25 17:25:04
我有一個清單input:[1, 2, 4, 3, 5, 7, 5, 3, 8, 3, 8, 5, 8, 5, 9, 5, 7, 5, 7, 4, 9, 7, 5, 7, 4, 7, 4, 7, 8, 9, 7, 5, 7, 5, 4, 9, 3, 4, 8, 4, 8, 5, 3, 5, 4, 7, 3, 7, 3, 1, 2, 7, 1, 7, 2, 1]我需要檢查 a 的元素是否lookup_list [1,2,3,4,5,7,8,9,5,4,3,2,1]以相同的順序以分散的方式出現在上面的列表中。這將說明我想說的話:[1, 2, 4, 3, 5, 7, 5, 3, 8, 3, 8, 5, 8, 5, 9, 5, 7, 5, 7, 4, 9, 7, 5, 7, 4, 7, 4, 7, 8, 9, 7, 5, 7, 5, 4, 9, 3, 4, 8, 4, 8, 5, 3, 5, 4, 7, 3, 7, 3, 1, 2, 7, 1, 7, 2, 1]粗體數字是列表中順序相同的lookup_list當前數字,但中間還有其他不相關的項目。input有什么辦法可以檢查這個嗎?這是我試過的方法:count = 0a = 0indices = []for item in list:    idx = -1    if count < len(input_list):        idx = list.index(input_list[count])        if idx != -1:            a = a +len(list[:idx])            list = list[idx:]            indices.append(a + idx)    count = count +1print(indices)但它給了我以下結果:[0, 2, 5, 35, 25, 24, 33, 30, 33, 37, 38, 64, 54]lookup_list問題是,此方法中未維護的順序。
查看完整描述

3 回答

?
Smart貓小萌

TA貢獻1911條經驗 獲得超7個贊

您可以在輸入列表上使用迭代器。調用next以獲取每個值。如果您用盡迭代器而沒有找到所有匹配項,您將得到 aStopIteration然后返回False。


def check(input_, lookup_list):

    it = iter(input_)

    try:

        for i in lookup_list:

            # read values from the input list until we find one which 

            # matches the current value from the lookup list

            while next(it) != i: 

                pass

        # we found matches for everything on the lookup list

        return True

    except StopIteration:

        # we tried to go past the end of the input list

        return False


查看完整回答
反對 回復 2023-04-25
?
拉風的咖菲貓

TA貢獻1995條經驗 獲得超2個贊

def check_exists(l, lookup_list):

check = True

for i in lookup_list:

    try:

        index = l.index(i) 

        l = l[index+1:]

    except ValueError:

        check = False 

        break 

return check

check_exists()函數將接受完整列表和查找列表作為參數,如果序列存在則返回 True,否則返回 false。


這是完整的程序-


def check_exists(l, lookup_list):

    check = True

    for i in lookup_list:

        try:

            index = l.index(i) 

            l = l[index+1:]

        except ValueError:

            check = False 

            break 

    return check




l = [1, 2, 4, 3, 5, 7, 5, 3, 8, 3, 8, 5, 8, 5, 9, 5, 7, 5, 7, 4, 9, 7, 5, 7, 

4, 7, 4, 7, 8, 9, 7, 5, 7, 5, 4, 9, 3, 4, 8, 4, 8, 5, 3, 5, 4, 7, 3, 7, 3, 1, 

2, 7, 1, 7, 2, 1]

lookup_list = [2,3,4,5,7,8,9,5,4,3,2,1] 


print(check_exists(l,lookup_list))


查看完整回答
反對 回復 2023-04-25
?
繁星淼淼

TA貢獻1775條經驗 獲得超11個贊

最簡單的方法是將第一個列表(不要稱它為!)轉換字符串input(尖括號將多位數字“放在一起”):

input_str = "".join("<"+str(i)+">" for i in input_list)

將第二個列表轉換為正則表達式,允許在必需項之間添加可選的附加項:

lookup_str = ".*" + ".+".join("<"+str(i)+">" for i in lookup_list) + ".+"

現在,檢查輸入字符串是否與正則表達式匹配:

if (re.search(lookup_str, input_str)): # there is a match


查看完整回答
反對 回復 2023-04-25
  • 3 回答
  • 0 關注
  • 220 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號