检查一个列表是否以另一个列表的元素开头 [英] Check whether a list starts with the elements of another list

查看:71
本文介绍了检查一个列表是否以另一个列表的元素开头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果列表的开头正好是另一个列表的元素,最容易检查(最Python方式)的方法是什么?请考虑以下示例:

What is the easiest (most pythonic way) to check, if the beginning of the list are exactly the elements of another list? Consider the following examples:

li = [1,4,5,3,2,8]

#Should return true
startsWithSublist(li, [1,4,5])

#Should return false
startsWithSublist(list2, [1,4,3])

#Should also return false, although it is contained in the list
startsWithSublist(list2, [4,5,3])

当然,我可以遍历列表,但是我想有一种更简单的方法.两个列表永远不会包含两次相同的元素,第二个列表将总是比第一个列表短或相等.要匹配的列表的长度是可变的.

Sure I could iterate over the lists, but I guess there is an easier way. Both list will never contain the same elements twice, and the second list will always be shorter or equal long to the first list. Length of the list to match is variable.

如何在Python中执行此操作?

How to do this in Python?

推荐答案

使用列表切片:

>>> li = [1,4,5,3,2,8]
>>> sublist = [1,4,5]
>>> li[:len(sublist)] == sublist
True

这篇关于检查一个列表是否以另一个列表的元素开头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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