2

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 3

4
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)
Sign up to request clarification or add additional context in comments.

Comments

2
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)

Comments

2

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']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.