简体   繁体   中英

Finding a sequence in list using another list In Python

I have a list = [0, 0, 7] and I when I compare it against anotherList = [0, 0, 7, 0] using in it gives me False .

I would like to know how I can check if numbers in one list are in the same sequence as another list.

So, if I do anotherList2 = [7, 0, 0, 0] :

list in anotherList2 returns False

But, list in anotherList return True

Here's a one-liner function that will check if list a is in list 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
>>>

You have to check each position in the list one by one. start iterating through anotherList

if the first element of list is same as the current element in the anotherList start checking until you find the whole sequence

The program goes here:

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)

Using slices it's pretty simple to write an efficient function that does what you're looking for:

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

Which we can use like this:

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

There are some great answers here, but here's another way you could tackle it using strings as a medium.

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

This basically turns the elements of the lists into strings and uses the in operator, which does what you'd expect in this case, checking whether l1 is in l2 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM