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

时间:2018-06-23 03:58:16

标签: python nested-lists

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

例如:

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

1 个答案:

答案 0 :(得分:0)

使用import { Component } from '@angular/core'; @Component({ selector: 'btn-shared', templateUrl: 'src/shared/btn.component.html' }) export class btnComponent { public FunctionOnClick(){ alert("Clicked "); } } 肯定不会保留顺序,因为集合是无序的。

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

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