如何获取另一个列表中包含相同项目的列表索引?

How to obtain the list's index that contain same items in another list?

我有一个列表列表和另一个单独的列表,我需要检查第二个列表的项目是否在列表列表的任何列表中以相同的顺序和 return 此类子列表的索引。

例如:

lst=[['ahmad','a',5],['ahmad','b',6],['ahmad','x',4],['Emme','b',5],['Emme','b',4]]

lst_2=['ahmad','b'],lst_3= ['b','ahmad'].

想要的结果:

在lst_2的情况下:

True
1

至于lst_3:

False

我尝试了以下行来检查单独列表是否在嵌套列表中,但结果未考虑顺序:

any(set(lst_2) <= set(l) for l in lst)

True

any(set(lst_3) <= set(l) for l in lst)

True

使用 set 肯定不会保留顺序,因为集合是无序的。

相反,我建议遍历列表并将子列表视为一个堆栈,每次匹配时您都会从中弹出一个元素。如果堆栈在任何时候都是空的,那么您将得到一个有序的子列表。

使用 deque 允许在 O(1).

中从 sublst 的左侧弹出

代码

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]