簡體   English   中英

在Python中使用另一個列表在列表中查找序列

[英]Finding a sequence in list using another list In Python

我有一個list = [0, 0, 7]和我的時候我比較反對它anotherList = [0, 0, 7, 0]使用in它給了我False

我想知道如何檢查一個列表中的數字是否與另一個列表相同。

因此,如果我執行anotherList2 = [7, 0, 0, 0]

list in anotherList2返回False

但是, list in anotherList返回True

這是一個單線函數,它將檢查列表a是否在列表b

>>> def list_in(a, b):
...     return any(map(lambda x: b[x:x + len(a)] == a, range(len(b) - len(a) + 1)))
...
>>> a = [0, 0, 7]
>>> b = [1, 0, 0, 7, 3]
>>> c = [7, 0, 0, 0]
>>> list_in(a, b)
True
>>> list_in(a, c)
False
>>>

您必須一一檢查清單中的每個位置。 開始遍歷anotherList

如果list的第一個元素與anotherList中的當前元素相同,則開始檢查直到找到整個序列

該程序在這里:

def list_in(list,anotherList):
    for i in range(0,len(anotherList)):
        if(list[0]==anotherList[i]):
            if(len(anotherList[i:]) >= len(list)):
                c=0
                for j in range(0,len(list)):
                    if(list[j]==anotherList[j+i]):
                        c += 1
                        if(c==len(list)):
                            print("True")
                            return
                    else:
                        continue


    print("False")
    return
list = [0,0,7]
anotherList = [0,0,7,0]
anotherList2 = [7,0,0,0]

list_in(list,anotherList)
list_in(list,anotherList2)

使用切片,編寫高效的函數可以輕松實現所需的功能:

def sequence_in(seq, target):
    for i in range(len(target) - len(seq) + 1):
        if seq == target[i:i+len(seq)]:
            return True
    return False

我們可以這樣使用:

sequence_in([0, 1, 2], [1, 2, 3, 0, 1, 2, 3, 4])

這里有一些很好的答案,但是這是您可以使用字符串作為媒介來解決它的另一種方法。

def in_ist(l1, l2):
    return ''.join(str(x) for x in l1) in ''.join(str(y) for y in l2)

基本上,這會將列表中的元素轉換為字符串,並使用in運算符,它會檢查l1是否在l2 ,從而達到您在這種情況下的預期。

暫無
暫無

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

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