![](/img/trans.png)
[英]Check whether a list starts with the elements of another list and if found return both the values together
[英]Check whether a list starts with the elements of another list
如果列表的開頭恰好是另一個列表的元素,那么檢查的最簡單(最pythonic方式)是什么? 請考慮以下示例:
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])
當然我可以迭代列表,但我想有一種更簡單的方法。 兩個列表永遠不會包含兩次相同的元素,第二個列表將始終比第一個列表更短或更長。 要匹配的列表長度是可變的。
如何在Python中執行此操作?
使用列表切片:
>>> li = [1,4,5,3,2,8]
>>> sublist = [1,4,5]
>>> li[:len(sublist)] == sublist
True
你可以使用all
而不切片並創建另一個列表:
def startsWithSublist(l,sub):
return len(sub) <= l and all(l[i] == ele for i,ele in enumerate(sub))
如果找到不匹配的元素,它將短路;如果所有元素都相同,則返回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.