python - 有没有一种有效的方法来搜索一个列表,另一个列表维护列表的顺序?
问题描述
我刚开始学习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
这可以按预期工作,但是占用了很多行,我正在寻找一种有效的方法来实现相同的结果。谢谢您的帮助。
解决方案
您可以创建如下内容:
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
推荐阅读
- javascript - 跟踪组件内数组更改的最佳方法是什么?
- html - 如何居中引导 jumbotron
- sparql - SPARQL:将多个谓词值组合成标签数组
- python - fractions.Fraction f 字符串作为带有 __format__ 的浮点数
- c# - 绑定到业务逻辑类时如何修复 ArgumentException
- php - 请求明确给定的 IP,但使用明确给定的主机名来进行 SSL 验证?
- php - Drush 允许的内存大小为 2097152 字节已用尽
- r - r studio中的图例符号和文本间距问题
- jsp - 如何将此选中的项目发送到另一个页面上显示?JSP 伺服器
- parameters - 训练 word2vec 时出现内存错误:分层 softmax