检查 Python 中是否存在切片列表 [英] Check for presence of a sliced list in Python

查看:40
本文介绍了检查 Python 中是否存在切片列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个函数来确定一个子列表是否存在于更大的列表中.

I want to write a function that determines if a sublist exists in a larger list.

list1 = [1,0,1,1,1,0,0]
list2 = [1,0,1,0,1,0,1]

#Should return true
sublistExists(list1, [1,1,1])

#Should return false
sublistExists(list2, [1,1,1])

有没有可以做到这一点的 Python 函数?

Is there a Python function that can do this?

推荐答案

如果您确定您的输入将只包含单个数字 0 和 1,那么您可以转换为字符串:

If you are sure that your inputs will only contain the single digits 0 and 1 then you can convert to strings:

def sublistExists(list1, list2):
    return ''.join(map(str, list2)) in ''.join(map(str, list1))

这会创建两个字符串,因此它不是最有效的解决方案,但由于它利用了 Python 中优化的字符串搜索算法,因此对于大多数用途来说可能已经足够了.

This creates two strings so it is not the most efficient solution but since it takes advantage of the optimized string searching algorithm in Python it's probably good enough for most purposes.

如果效率非常重要,您可以查看 Boyer-Moore 字符串搜索算法,适用于列表.

If efficiency is very important you can look at the Boyer-Moore string searching algorithm, adapted to work on lists.

简单搜索有 O(n*m) 最坏的情况,但如果您不能使用转换为字符串的技巧并且不需要担心性能,则可能是合适的.

A naive search has O(n*m) worst case but can be suitable if you cannot use the converting to string trick and you don't need to worry about performance.

这篇关于检查 Python 中是否存在切片列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆