[英]How to check if one list starts with another?
If I have two lists in Python, [0, 1]
and [0, 1, 2, 3]
, how do I check if the first list starts with the second?如果我在 Python 中有两个列表
[0, 1]
和[0, 1, 2, 3]
,如何检查第一个列表是否以第二个列表开头?
I know how to do this with strings, just use the startswith
method.我知道如何使用字符串执行此操作,只需使用
startswith
方法即可。 But apparently you can't do that for lists.但显然你不能对列表这样做。
Is there a one-liner that does what I described?有没有一种单线可以完成我所描述的?
Just iterate them parallelly and check that the corresponding values are equal.只需并行迭代它们并检查相应的值是否相等。 You can create a generator expression for the equality iterating using
zip
, along with all
:您可以使用
zip
以及all
为等式迭代创建一个生成器表达式:
>>> a = [0, 1]
>>> b = [0, 1, 2, 3]
>>> all(i==j for i,j in zip(a,b))
True
This works because zip
stops when the shortest iterable is exhausted.这是有效的,因为
zip
在最短的迭代器耗尽时停止。
>>> a = [0, 1] >>> b = [0, 1, 2, 3] >>> a[:min(len(a), len(b))] == b[:min(len(a), len(b))] True
I think this is what you meant我想这就是你的意思
if the list x starts with the list y
>>> x[0:len(y)] == y
True
>>> x
[0, 1, 2, 3]
>>> y
[0, 1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.