Indexing a list with an unique index

后端 未结 6 616
清歌不尽
清歌不尽 2020-11-30 08:52

I have a list say l = [10,10,20,15,10,20]. I want to assign each unique value a certain \"index\" to get [1,1,2,3,1,2].

This is my code:

6条回答
  •  死守一世寂寞
    2020-11-30 09:03

    Your solution is slow because its complexity is O(nm) with m being the number of unique elements in l: a.index() is O(m) and you call it for every element in l.

    To make it O(n), get rid of index() and store indexes in a dictionary:

    >>> idx, indexes = 1, {}
    >>> for x in l:
    ...     if x not in indexes:
    ...         indexes[x] = idx
    ...         idx += 1
    ... 
    >>> [indexes[x] for x in l]
    [1, 1, 2, 3, 1, 2]
    

    If l contains only integers in a known range, you could also store indexes in a list instead of a dictionary for faster lookups.

提交回复
热议问题