Assign a number to each unique value in a list

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

    Since you are mapping strings to integers, that suggests using a dict. So you can do the following:

    d = dict()
    
    counter = 0
    
    for name in names:
        if name in d:
            continue
        d[name] = counter
        counter += 1
    
    numbers = [d[name] for name in names]
    

提交回复
热议问题