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

python-有没有一种有效的方法来搜索列表,而另一个列表保持列表的顺序?,第1张

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

我才刚刚开始学习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 = 0Pos1 = 0Pos2 = 1Pos3 = 2Pos4 = 3Pos5 = 4Pos6 = 5Pos1A = 0Pos2A = 1Pos3A = 2Pos4A = 3Pos5A = 4Pos6A = 5while 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 总结

以上是内存溢出为你收集整理的python-有没有一种有效的方法来搜索列表,而另一个列表保持列表的顺序? 全部内容,希望文章能够帮你解决python-有没有一种有效的方法来搜索列表,而另一个列表保持列表的顺序? 所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/langs/1199669.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-04
下一篇 2022-06-04

发表评论

登录后才能评论

评论列表(0条)

保存