代码之家  ›  专栏  ›  技术社区  ›  Ahmad Senousi

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

  •  -1
  • Ahmad Senousi  · 技术社区  · 8 年前

    我有一个列表和另一个单独的列表,我需要检查第二个列表中的项目是否在列表的任何列表中 按同样的顺序 并返回这些子列表的索引。

    例如:

    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
    

    至于第三层:

    False
    

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

    any(set(lst_2) <= set(l) for l in lst)
    
    True
    
    any(set(lst_3) <= set(l) for l in lst)
    
    True
    
    1 回复  |  直到 8 年前
        1
  •  0
  •   Olivier Melançon iacob    8 年前

    使用 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]