Indexing a list with an unique index

后端 未结 6 620
清歌不尽
清歌不尽 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:19

    The slowness of your code arises because a.index(x) performs a linear search and you perform that linear search for each of the elements in l. So for each of the 1M items you perform (up to) 100K comparisons.

    The fastest way to transform one value to another is looking it up in a map. You'll need to create the map and fill in the relationship between the original values and the values you want. Then retrieve the value from the map when you encounter another of the same value in your list.

    Here is an example that makes a single pass through l. There may be room for further optimization to eliminate the need to repeatedly reallocate res when appending to it.

    res = []
    conversion = {}
    i = 0
    for x in l:
        if x not in conversion:
            value = conversion[x] = i
            i += 1
        else:
            value = conversion[x]
        res.append(value)
    

提交回复
热议问题