Python Map List of Strings to Integer List

后端 未结 9 1271
猫巷女王i
猫巷女王i 2020-12-31 23:05

Let\'s say I have a list

l = [\'michael\',\'michael\',\'alice\',\'carter\']

I want to map it to the following:

k = [1,1,2,3         


        
9条回答
  •  無奈伤痛
    2020-12-31 23:30

    In order to answer the edited question, i.e., to map the list of strings to unique integers, one has to first find the unique strings and then do 1-1 mapping of the strings to integers in the original list of strings. For example,

    s = ['michael','michael','alice','carter']
    

    then unique strings are {'michael','alice','carter'}. Now, convert these strings to integers by 1-1 mapping like {'michael','alice','carter'} =[1,2,3] using dictionary {'michael':1,'alice':2,'carter':3}. In the third step, loop through the original list of strings; search the string in the dictionary for the corresponding integer and replace the string by that integer.

    s=['michael','michael','alice','carter']
    
    mydict={}
    i = 0
    for item in s:
        if(i>0 and item in mydict):
            continue
        else:    
           i = i+1
           mydict[item] = i
    
    k=[]
    for item in s:
        k.append(mydict[item])
    

    Output:

    k=[1, 1, 2, 3]
    

提交回复
热议问题