[英]Check whether a list starts with the elements of another list
What is the easiest (most pythonic way) to check, if the beginning of the list are exactly the elements of another list? 如果列表的开头恰好是另一个列表的元素,那么检查的最简单(最pythonic方式)是什么? 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.
要匹配的列表长度是可变的。
How to do this in Python? 如何在Python中执行此操作?
Use list slicing: 使用列表切片:
>>> li = [1,4,5,3,2,8]
>>> sublist = [1,4,5]
>>> li[:len(sublist)] == sublist
True
You can do it using all
without slicing and creating another list: 你可以使用
all
而不切片并创建另一个列表:
def startsWithSublist(l,sub):
return len(sub) <= l and all(l[i] == ele for i,ele in enumerate(sub))
It will short circuit if you find non-matching elements or return True if all elements are the same, you can also use itertools.izip
: 如果找到不匹配的元素,它将短路;如果所有元素都相同,则返回True,您也可以使用
itertools.izip
:
from itertools import izip
def startsWithSublist(l,sub):
return len(sub) <= l and all(a==b for a,b in izip(l,sub))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.