Assign a number to each unique value in a list

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

    If you have k different values, this maps them to integers 0 to k-1 in order of first appearance:

    >>> names = ['b', 'c', 'd', 'c', 'b', 'a', 'b']
    >>> tmp = {}
    >>> [tmp.setdefault(name, len(tmp)) for name in names]
    [0, 1, 2, 1, 0, 3, 0]
    

提交回复
热议问题