Home > Mobile >  Sort python list based on substring in separate list
Sort python list based on substring in separate list

Time:08-19

I have 2 lists..

list_a = ['Grapes/testfile.csv','Apples/testfile.csv','Pears/testfile.csv','Pears/testfile2.csv']
ref_list = ['Pears','Grapes','Apples']

I need to use ref_list list to order list_a.

More context, list_a will always have the string from ref_list before the / but the length of ref_list will never match that of list_a.. Also I dont want to order reverse alphabetically.

Expected Output:

ordered_list = ['Pears/testfile.csv','Pears/testfile2.csv','Grapes/testfile.csv','Apples/testfile.csv']

I've tried many variations, referencing SO but I cant get this to work.. I just cant work out a way to reference the first list here is my attempt which obviously doesn't work as its not referencing ref_list but my logic is to use string method startswith()

Something like:?

ordered_list = sorted(list_a, key = lambda x: x.startswith())

CodePudding user response:

Use split() to extract the word before /.

Then use index() to get the position of the starting word in ref_list, and use that for the sorting key.

ordered_list = sorted(list_a, key = lambda x: ref_list.index(x.split('/')[0]))

CodePudding user response:

This answer may not be the most elegant, but it works:

sorted_list = list()

for key in ref_list:

sorted_list = [sorted_value for sorted_value in list_a if \

sorted_value.startswith(key)]

  • Related