Indexing a list with an unique index

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

    You can use collections.OrderedDict() in order to preserve the unique items in order and, loop over the enumerate of this ordered unique items in order to get a dict of items and those indices (based on their order) then pass this dictionary with the main list to operator.itemgetter() to get the corresponding index for each item:

    >>> from collections import OrderedDict
    >>> from operator import itemgetter
    >>> itemgetter(*lst)({j:i for i,j in enumerate(OrderedDict.fromkeys(lst),1)})
    (1, 1, 2, 3, 1, 2)
    

提交回复
热议问题