加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python-有没有一种有效的方法来搜索列表,而另一个列表保持列表的

发布时间:2020-12-17 17:40:57 所属栏目:Python 来源:网络整理
导读:我才刚刚开始学习python. 我需要搜索另一个列表,但是我必须保持搜索列表的顺序.例如: MylistA = [A,B,G,S,X]MylistB = [A,B] 我希望它返回false,因为ListB与ListA的顺序不同.但是,如果是: ListA =[A,X]ListB =[A,G] 我希望它返回True. 以下是我尝试过的方

我才刚刚开始学习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

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

最佳答案
您可以创建如下内容:

ListA = ["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

Demo

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读