min2bro
min2bro

Reputation: 4638

Sorting list based on Search Query

I have a list of strings and I have to sort it based on some search string.

My Search String is Home Depot

MyList = ['Depot Home','Rollins Home Furniture','HomeDepot 1346','Home Depot']

Expected Output:

Sorted list: ['HomeDepot 1346','Home Depot','Depot Home','Rollins Home Furniture']

In the sorted list first element is exact match of search string removing spaces, Second is also exact Match with space and 3rd element is partial Match of Depot(in alphabetical order) and 4th element is also a partial match for Home (alphabetical order so placed after Depot)

What I did so far:

searchquery_startswith=[w for w in Mylist if w.startswith('HOME DEPOT'.strip())]
searchquery_substring= [w for w in Mylist if ('HOME DEPOT' in w and w not in searchquery_startswith)]

I know I can do something like this but I'm looking for more pythonic way to achieve this. All help appreciated

Upvotes: 0

Views: 138

Answers (1)

Markus
Markus

Reputation: 684

You can define a custom function that ranks your words given your search query and then use this in combination with sorted.

def search_for_home_depot(word):
    result = 0
    if word.lower().startswith('HOME DEPOT'.lower().replace(' ','')):
        result += -2

    if 'HOME DEPOT'.lower() in word.lower():
        result += -1

    return result

l = ['Depot Home','Rollins Home Furniture','HomeDepot 1346','Home Depot']

print([search_for_home_depot(x) for x in l])

print(sorted(l, key=search_for_home_depot))

> [0, 0, -2, -1]
> ['HomeDepot 1346', 'Home Depot', 'Depot Home', 'Rollins Home Furniture']

You can adapt the conditions and weightings of each individual check to finegrain your results.

Upvotes: 1

Related Questions