我才刚刚开始学习python.
我需要搜索另一个列表,但是我必须保持搜索列表的顺序.例如:
MylistA = [A,B,G,S,X]
MylistB = [A,B]
我希望它返回false,因为ListB与ListA的顺序不同.但是,如果是:
ListA =[A,X]
ListB =[A,G]
我希望它返回True.
以下是我尝试过的方法,但是它占用了很多行并且效率很低.
MylistA = [A,Q,V,D,F,R,T,Q]
MylistB = [B,T]
ListFound = 0
Pos1 = 0
Pos2 = 1
Pos3 = 2
Pos4 = 3
Pos5 = 4
Pos6 = 5
Pos1A = 0
Pos2A = 1
Pos3A = 2
Pos4A = 3
Pos5A = 4
Pos6A = 5
while Pos6 <= len(MylistA):
if MylistA[pos1] == MylistB[Pos1A] and \
MylistA[pos2] == MylistB[Pos2A] and \
MylistA[pos3] == MylistB[Pos3A] and \
MylistA[pos4] == MylistB[Pos4A] and \
MylistA[pos5] == MylistB[Pos5A] and \
MylistA[pos6] == MylistB[Pos6A]:
print("MylistB found within MylistA at positions",Pos1,Pos2,Pos3,Pos4,Pos5,Pos6)
MylistFound += 1
elif Pos6 >= len(ListA):
print("MylistB was found",ListFound,"times within MylistA")
Pos1 += 1
Pos2 += 1
Pos3 += 1
Pos4 += 1
Pos5 += 1
Pos6 += 1
但是,这按预期工作,但是占用了很多行,我正在寻找一种有效的方法来实现相同的结果.谢谢您的帮助.
最佳答案
您可以创建如下内容:
原文链接:https://www.f2er.com/python/533276.htmlListA = ["A","Q","V","B","G","D","F","R","T","S","Q"]
ListB = ["B","T"]
for x in range(0,len(ListA)):
if ListA[x:len(ListB)+x] == ListB:
print("Full Match",ListA[x:len(ListB)+x])
print("Positions","{}:{}".format(x,len(ListB)+x))
break
# Full Match ['B','G','D','F','R','T']
# Positions 3:9 # last value (9) is exclusive