【问题标题】:Finding a sequence in list using another list In Python在Python中使用另一个列表查找列表中的序列
【发布时间】:2018-12-05 19:05:58
【问题描述】:

我有一个list = [0, 0, 7],当我使用in 将它与anotherList = [0, 0, 7, 0] 进行比较时,它给了我False

我想知道如何检查一个列表中的数字是否与另一个列表的顺序相同。

所以,如果我这样做anotherList2 = [7, 0, 0, 0]

list in anotherList2 返回 False

但是,list in anotherList 返回 True

【问题讨论】:

  • 你不应该列出list,它会覆盖一个内置名称。此外,list in anotherList 将在此处返回 False,而不是 True
  • 在这种情况下,in 检查列表是否为anotherList 的元素,而不是list 的元素是否包含在anotherList 中。如果你先anotherList.append(list) 然后list in anotherList,你会看到它返回True
  • 在更大的数据集上构造一个滑动窗口迭代器,看看是否有任何窗口等于您的第一个列表:stackoverflow.com/questions/6822725/…

标签: python list comparison comparison-operators


【解决方案1】:

您必须一一检查列表中的每个位置。 开始遍历 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)

【讨论】:

  • 当列表包含多个数字并且列表中两个数字的相邻数字恰好与另一个列表中两个不同数字的数字匹配时,这将给出误报。例如,[12, 3][1, 23] 将使用您的方法匹配,这是不正确的。
  • 是的,我已经通过创建一个函数并一个一个地检查每个数字来解决它
【解决方案2】:

使用切片编写一个高效的函数来满足您的需求非常简单:

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])

【讨论】:

  • 编辑:根据@blhsing 的回答更改范围长度。比起any/map 还是更喜欢这个,所以会离开这里。
【解决方案3】:

这是一个单行函数,它将检查列表 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
>>>

【讨论】:

  • 你能解释一下 lambda 函数吗?
【解决方案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 中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多