Home > OS >  Rearrange a list of strings based on its sorted list in python
Rearrange a list of strings based on its sorted list in python

Time:12-25

So i have an initial list of strings l and i want to rearrange it based on the positions of o so i can get the outcome as seen in n. I was thinking of enumerating the l and somehow rearrange based on the enumerated o.

I want this to be a function that works with any inputed list of strings like this for example:

l = ['cbc', 'adb', 'dab', 'acb', 'bbc', 'aca', 'bbb', 'aab', 'cad', 'bba']

print (f(l)) #Prints : ['aab', 'aca', 'bba', 'acb', 'adb', 'dab', 'cad', 'bbb', 'bbc', 'cbc'] 

This is what i got so far and i am stuck on the rearranging part.

def f(x):
    transition_string = []
    for i in x:
        k_string = "".join(sorted(i))
        transition_string.append(k_string)
    print(transition_string) #This prints k 
    print(sorted(transition_string)) #This prints o
    enu_list = list(enumerate(sorted(''.join(sorted(j)) for j in transition_string))) #This is O

l = ['be', 'tc', 'ka'] #Initial list
k = ['be', 'ct', 'ak'] #Each element is sorted and keeps position
o = ['ak', 'be', 'ct'] #This is the sorted(k)
n = ['ka', 'be', 'tc'] #Wanted outcome

CodePudding user response:

I hope the below code would be helpful; Kindly refer the comments for your reference.

def transition(l):                    # Get Initial List
  k = ["".join(sorted(i)) for i in l] # Sort Individual Strings in List l
  map = [(x,y) for (x,y) in zip(l,k)]   # Create a map for l and k as it preserves position
  sort_map_with_k = sorted(map, key = lambda x : x[1]) # Sort the map with values at index [1] as they are from k
  #As we already sorted the map with k, the sorted maps first values will contain the elements of rearranged_list
  n = [m[0] for m in sort_map_with_k]
  return n #Result returned.

Example with your input

l = ['cbc', 'adb', 'dab', 'acb', 'bbc', 'aca', 'bbb', 'aab', 'cad', 'bba']

Result :

['aab', 'aca', 'bba', 'acb', 'adb', 'dab', 'cad', 'bbb', 'bbc', 'cbc']

CodePudding user response:

If you don't care about having efficient code, a simple and easy to follow solution is this:

k = ["".join(sorted(s)) for s in l]
lk_tuples = [(a,b) for (a,b) in zip(l,k)]
lk_tuples_sorted_by_k = sorted(lk_tuples, key=lambda x: x[1])
n = [val[0] for val in lk_tuples_sorted_by_k]

It can also be made into a single liner but I never see the point in that, it will just make it more difficult to read. And it can also be made a lot more efficient but the first draft of a solution is better to make it simple IMO.

CodePudding user response:

def f(x):
    k = ["".join(sorted(el)) for el in x]
    o = sorted(k)
    index_map = {el:i for i,el in enumerate(o)}
    n = [0]*len(x)
    for i,el in enumerate(k):
        n[index_map[el]] = x[i]
    return n
  • Related