Assign a number to each unique value in a list

前端 未结 8 1311
名媛妹妹
名媛妹妹 2020-12-03 03:28

I have a list of strings. I want to assign a unique number to each string (the exact number is not important), and create a list of the same length using these numbers, in o

8条回答
  •  不思量自难忘°
    2020-12-03 04:22

    Here is a similar factorizing solution with collections.defaultdict and itertools.count:

    import itertools as it
    import collections as ct
    
    
    names = ['ll', 'll', 'hl', 'hl', 'LL', 'LL', 'LL', 'HL', 'll']
    
    dd = ct.defaultdict(it.count().__next__)
    [dd[i] for i in names]
    # [0, 0, 1, 1, 2, 2, 2, 3, 0]
    

    Every new occurrence calls the next integer in itertools.count and adds new entry to dd.

提交回复
热议问题