使用
set
一定不会保留顺序,因为集合是无序的。
相反,我建议遍历列表,并将子列表视为一个堆栈,每次匹配时都从该堆栈弹出一个元素。如果堆栈在任何时候都是空的,那么就得到一个有序的子列表。
A的使用
deque
允许从左侧弹出
sublst
在里面
O(一)
是的。
代码
from collections import deque
def is_ordered_sublist(sublst, lst):
sublst = deque(sublst)
for x in lst:
if not sublst:
# return True early if the stack is empty
return True
if x == sublst[0]:
sublst.popleft()
return not sublst
实例
print(is_ordered_sublist([1, 2, 3], [1, 9, 2, 9, 3, 9])) # True
print(is_ordered_sublist([1, 2, 3], [1, 9, 3, 9, 2, 9])) # False
恢复子列表索引
然后,您可以使用上面的函数来理解列表并
enumerate
恢复相应的指数。
lst=[['ahmad','a',5],['ahmad','b',6],['ahmad','x',4],['Emme','b',5],['Emme','b',4]]
lst_2=['ahmad','b']
indices = [i for i, l in enumerate(lst) if is_ordered_sublist(lst_2, l)]
print(indices) # [1]