Assign a number to each unique value in a list

前端 未结 8 1302
名媛妹妹
名媛妹妹 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.

    0 讨论(0)
  • 2020-12-03 04:25

    You can Try This Also:-

    names = ['ll', 'll', 'll', 'hl', 'hl', 'hl', 'LL', 'LL', 'LL', 'HL', 'HL', 'HL']
    
    indexList = list(set(names))
    
    print map(lambda name:indexList.index(name),names)
    
    0 讨论(0)
提交回复
热议问题