3 回答
TA贡献1911条经验 获得超7个赞
您可以在输入列表上使用迭代器。调用next以获取每个值。如果您用尽迭代器而没有找到所有匹配项,您将得到 aStopIteration然后返回False。
def check(input_, lookup_list):
it = iter(input_)
try:
for i in lookup_list:
# read values from the input list until we find one which
# matches the current value from the lookup list
while next(it) != i:
pass
# we found matches for everything on the lookup list
return True
except StopIteration:
# we tried to go past the end of the input list
return False
TA贡献1995条经验 获得超2个赞
def check_exists(l, lookup_list):
check = True
for i in lookup_list:
try:
index = l.index(i)
l = l[index+1:]
except ValueError:
check = False
break
return check
check_exists()函数将接受完整列表和查找列表作为参数,如果序列存在则返回 True,否则返回 false。
这是完整的程序-
def check_exists(l, lookup_list):
check = True
for i in lookup_list:
try:
index = l.index(i)
l = l[index+1:]
except ValueError:
check = False
break
return check
l = [1, 2, 4, 3, 5, 7, 5, 3, 8, 3, 8, 5, 8, 5, 9, 5, 7, 5, 7, 4, 9, 7, 5, 7,
4, 7, 4, 7, 8, 9, 7, 5, 7, 5, 4, 9, 3, 4, 8, 4, 8, 5, 3, 5, 4, 7, 3, 7, 3, 1,
2, 7, 1, 7, 2, 1]
lookup_list = [2,3,4,5,7,8,9,5,4,3,2,1]
print(check_exists(l,lookup_list))
TA贡献1775条经验 获得超11个赞
最简单的方法是将第一个列表(不要称它为!)转换为字符串input
(尖括号将多位数字“放在一起”):
input_str = "".join("<"+str(i)+">" for i in input_list)
将第二个列表转换为正则表达式,允许在必需项之间添加可选的附加项:
lookup_str = ".*" + ".+".join("<"+str(i)+">" for i in lookup_list) + ".+"
现在,检查输入字符串是否与正则表达式匹配:
if (re.search(lookup_str, input_str)): # there is a match
添加回答
举报