Assign a number to each unique value in a list

前端 未结 8 1323
名媛妹妹
名媛妹妹 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:12

    If the condition is that the numbers are unique and the exact number is not important, then you can build a mapping relating each item in the list to a unique number on the fly, assigning values from a count object:

    from itertools import count
    
    names = ['ll', 'll', 'hl', 'hl', 'LL', 'LL', 'LL', 'HL', 'll']
    
    d = {}
    c = count()
    numbers = [d.setdefault(i, next(c)) for i in names]
    print(numbers)
    # [0, 0, 2, 2, 4, 4, 4, 7, 0]
    

    You could do away with the extra names by using map on the list and a count object, and setting the map function as {}.setdefault (see @StefanPochmann's comment):

    from itertools import count
    
    names = ['ll', 'll', 'hl', 'hl', 'LL', 'LL', 'LL', 'HL', 'll']
    numbers  = map({}.setdefault, names, count()) # call list() on map for Py3
    print(numbers)
    # [0, 0, 2, 2, 4, 4, 4, 7, 0]
    

    As an extra, you could also use np.unique, in case you already have numpy installed:

    import numpy as np
    
    _, numbers = np.unique(names, return_inverse=True)
    print(numbers)
    # [3 3 2 2 1 1 1 0 3]
    

提交回复
热议问题