简体   繁体   English

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

[英]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 . 我有一个list = [0, 0, 7]和我的时候我比较反对它anotherList = [0, 0, 7, 0]使用in它给了我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] : 因此,如果我执行anotherList2 = [7, 0, 0, 0]

list in anotherList2 returns False list in anotherList2返回False

But, list in anotherList return True 但是, list in anotherList返回True

Here's a one-liner function that will check if list a is in list b : 这是一个单线函数,它将检查列表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
>>>

You have to check each position in the list one by one. 您必须一一检查清单中的每个位置。 start iterating through anotherList 开始遍历anotherList

if the first element of list is same as the current element in the anotherList start checking until you find the whole sequence 如果list的第一个元素与anotherList中的当前元素相同,则开始检查直到找到整个序列

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 . 基本上,这会将列表中的元素转换为字符串,并使用in运算符,它会检查l1是否在l2 ,从而达到您在这种情况下的预期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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