list match in python: get indices of a sub-list in a larger list

前端 未结 2 1795
无人共我
无人共我 2021-02-09 07:04

For two lists,

a = [1, 2, 9, 3, 8, ...]   (no duplicate values in a, but a is very big)
b = [1, 9, 1,...]          (set(b) is a subset of set(a), 1<

        
2条回答
  •  无人及你
    2021-02-09 07:32

    Presuming we are working with smaller lists, this is as easy as:

    >>> a = [1, 2, 9, 3, 8] 
    >>> b = [1, 9, 1] 
    >>> [a.index(item) for item in b]
    [0, 2, 0]
    

    On larger lists, this will become quite expensive.

    (If there are duplicates, the first occurrence will always be the one referenced in the resulting list, if not set(b) <= set(a), you will get a ValueError).

提交回复
热议问题