Search code examples
pythonarrayssortingalphabetical

"rank" each character in a string by the index at which they appear in the alphabet


I don't know how to get for example from arr1 = ['johaj'] --> arr2 = ['2','4','1','0','3'] I'm not able to describe it very well what I mean so i hope you can understand it from this example. I need to get array of 'alphabetical indexes'.

I would be very grateful for solution, how can I do this in Python. Thank you

enter image description here


Solution

  • This will work for you:

    arr1 = ['johaj']
    
    arr2 = []
    for item in arr1:
      origins = list(zip(item, list(range(len(item)))))
      origins.sort()
      ranks = list(range(len(item)))
      positioned = {origin:rank for origin, rank in zip(origins, ranks)}
    
      ranked = [None] * len(item)
      for origin in origins:
        ranked[origin[1]] = positioned[origin]
      arr2.append(ranked)
    
    print(arr2)
    

    Output:

    [[2, 4, 1, 0, 3]]
    

    Because arr1 is an array, you have to iterate over that array to get each item. This means that arr2 will be a two-dimensional array that will return the ranks for each item in arr1. For example, if:

    arr1 = ['johaj', 'foo', 'bar']
    

    It will output:

    [[2, 4, 1, 0, 3], [0, 1, 2], [1, 0, 2]]