Indexing a list with an unique index

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

    For completness, you can also do it eagerly:

    from itertools import count
    
    wordid = dict(zip(set(list_), count(1)))
    

    This uses a set to obtain the unique words in list_, pairs each of those unique words with the next value from count() (which counts upwards), and constructs a dictionary from the results.

    Original answer, written by nneonneo.

提交回复
热议问题