Indexing a list with an unique index

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

    Well I guess it depends on if you want it to return the indexes in that specific order or not. If you want the example to return:

        [1,1,2,3,1,2]
    

    then you can look at the other answers submitted. However if you only care about getting a unique index for each unique number then I have a fast solution for you

        import numpy as np
        l = [10,10,20,15,10,20]
        a = np.array(l)
        x,y = np.unique(a,return_inverse = True)
    

    and for this example the output of y is:

        y = [0,0,2,1,0,2]
    

    I tested this for 1,000,000 entries and it was done essentially immediately.

提交回复
热议问题