首页 > 解决方案 > 有没有一种有效的方法来搜索一个列表,另一个列表维护列表的顺序?

问题描述

我刚开始学习python。我需要用另一个列表搜索一个列表,但我必须保持我正在搜索的列表的顺序。前任:

MylistA = [A, B, G, S, X]

MylistB = [A, G, B]

我希望它返回 false,因为ListB它的顺序与ListA. 但是,如果是:

ListA =[A, B, G, S, X]
ListB =[A, B, G]

我希望这个返回True

以下是我尝试过的,但是它占用了很多行并且效率低下。

MylistA = [A, Q, V, B, G, D, F, R, T, B, G, S, Q]
MylistB = [B, G, D, F, R, 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

这可以按预期工作,但是占用了很多行,我正在寻找一种有效的方法来实现相同的结果。谢谢您的帮助。

标签: pythonlist

解决方案


您可以创建如下内容:

ListA = ["A", "Q", "V", "B", "G", "D", "F", "R", "T", "B", "G", "S", "Q"]
ListB = ["B", "G", "D", "F", "R", "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

演示


推荐阅读