Assign a number to each unique value in a list

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

    To make it more generic you can wrap it in a function, so these hard-coded values don't do any harm, because they are local.

    If you use efficient lookup-containers (I'll use a plain dictionary) you can keep the first index of each string without loosing to much performance:

    def your_function(list_of_strings):
    
        encountered_strings = {}
        result = []
    
        idx = 0
        for astring in list_of_strings:
            if astring in encountered_strings:  # check if you already seen this string
                result.append(encountered_strings[astring])
            else:
                encountered_strings[astring] = idx
                result.append(idx)
                idx += 1
        return result
    

    And this will assign the indices in order (even if that's not important):

    >>> your_function(['ll', 'll', 'll', 'hl', 'hl', 'hl', 'LL', 'LL', 'LL', 'HL', 'HL', 'HL'])
    [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3]
    

    This needs only one iteration over your list of strings, which makes it possible to even process generators and similar.

提交回复
热议问题