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

前端 未结 2 1798
无人共我
无人共我 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:48

    A fast method (when a is a large list) would be using a dict to map values in a to indices:

    >>> index_dict = dict((value, idx) for idx,value in enumerate(a))
    >>> [index_dict[x] for x in b]
    [0, 2, 0]
    

    This will take linear time in the average case, compared to using a.index which would take quadratic time.

提交回复
热议问题