sorting a list of strings using another list of strings

Viewed 69

I have searched through stackoverflow but can't find a suitable solution, I have two list list_A and list_B. the strings in list_A are of varying length while list_B contains the last two or three char in list a that are unique

list_A = ['SedimentDB','SeedDB', 'FloorCD', 'QuanCD', 'DewDB', 'AsiaDMS', 'AfriDMS', 'EuroDMS'] 
List_B = ['DMS', 'CD', 'DB']

i would like to sort List_A based on the order of List_B.

the result should be similar to

List_A = ['AsiaDMS', 'AfriDMS', 'EuroDMS', 'FloorCD', 'QuanCD', 'SedimentDB','SeedDB', 'DewDB']

thanks.

3 Answers
def sortKey(text):
    for i,b in enumerate(List_B):
        if text.endswith(b):
            return i
    return len(List_B)
list_A.sort(key=sortKey)
List_A = ['SedimentDB','SeedDB', 'FloorCD', 'QuanCD', 'DewDB', 'AsiaDMS',
          'AfriDMS', 'EuroDMS']
List_B = ['DMS', 'CD', 'DB']
new_lst = []

for j in List_B:
    for i in range(0,len(List_A)):
        len_i = len(List_A[i]) # length of each word in LIst A
        len_j = len(j) #  length of each word in LIst b
        if List_A[i][len_i-len_j:]  == j :
            new_lst.append(List_A[i])

print(new_lst)

This is the shortest (and simplest) solution I could think of -

list_A = ['SedimentDB','SeedDB', 'FloorCD', 'QuanCD', 'DewDB', 'AsiaDMS', 'AfriDMS', 'EuroDMS'] 
List_B = ['DMS', 'CD', 'DB']

new_list = [x for y in List_B for x in list_A if y in x]
print (new_list)

Output:

['AsiaDMS', 'AfriDMS', 'EuroDMS', 'FloorCD', 'QuanCD', 'SedimentDB', 'SeedDB', 'DewDB']
Related