如何检查列表中是否存在子序列? [英] How to check subsequence exists in a list?
问题描述
在python中,可以使用is
关键字来检查包含内容,例如
In python, it's possible to use the is
keyword to check for contains, e.g.
>>> 3 in [1,2,3,4,5]
True
但是,如果要检查单个整数列表是否在引用列表[1,2,3,4,5]
中,则不会产生相同的输出:
But this doesn't yield the same output if it's checking whether a list of a single integer is inside the reference list [1,2,3,4,5]
:
>>> [3] in [1,2,3,4,5]
False
此外,使用以下方法无法检查参考列表中的子序列:
Also, checking a subsequence in the reference list cannot be achieved with:
>>> [3,4,5] in [1,2,3,4,5]
False
是否有一种方法可以检查子序列,以使以下结果返回true?,例如函数调用x_in_y()
:
>>> x_in_y([3,4,5], [1,2,3,4,5])
True
>>> x_in_y([3], [1,2,3,4,5])
True
>>> x_in_y(3, [1,2,3,4,5])
True
>>> x_in_y([2,3], [1,2,3,4,5])
True
>>> x_in_y([2,4], [1,2,3,4,5])
False
>>> x_in_y([1,5], [1,2,3,4,5])
False
也许来自itertools
或operator
?
Maybe something from itertools
or operator
?
(注意,输入列表可以是唯一的)
(Note, the input lists can be non-unique)
推荐答案
x_in_y()
可以通过切片原始列表并将切片与输入列表进行比较来实现:
x_in_y()
can be implemented by slicing the original list and comparing the slices to the input list:
def x_in_y(query, base):
try:
l = len(query)
except TypeError:
l = 1
query = type(base)((query,))
for i in range(len(base)):
if base[i:i+l] == query:
return True
return False
如果使用的是Python2,请将range
更改为xrange
.
Change range
to xrange
if you are using Python2.
这篇关于如何检查列表中是否存在子序列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!