简体   繁体   English

检查列表是否以另一个列表的元素开头

[英]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.

相关问题 检查列表是否以另一个列表的元素开头,如果找到,则将两个值一起返回 - Check whether a list starts with the elements of another list and if found return both the values together 检查列表的元素是否是另一个列表的元素的子集 - To check whether elements of a list is a subset of elements of another list 检查具有列表值的列的元素是否存在于另一个列表中 - Check whether the elements of a column with list values are present in another list 如何检查一个列表是否以另一个列表开头? - How to check if one list starts with another? 检查列表元素是否存在于另一个列表的元素中 - check if element of list is present in elements of another list 检查另一个列表中一个列表中的元素 - Check for elements in one list from another list 最佳检查列表的元素是否在 python 的另一个列表中 - Optimal check if the elements of a list are in another list in python 尝试根据元素是否在 Python 中的另一个列表中来过滤一个列表 - Trying to filter one list according to whether elements are in another list in Python 检查列表中的项是否存在于另一个列表中或不存在于python中 - Check whether an item in a list exist in another list or not python 删除列表中的重复项并检查它是否与另一个列表相同 - Remove duplicates in a list and check whether it's the same as another list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM