Home > Net >  Sort based on where the search string found
Sort based on where the search string found

Time:10-05

Is it possible to sort the search result based on where the search string is found? Basically I am using Django Rest and trying to show the results on top if the search string is found at the beginning.

For example,

values = [ "another test", "test", "something", "teeest"]
search_string="te"
result=["another test", "test", "teeest"]

I want to bring the last two in the front as it has "te" at the begining like

result=[ "test", "teeest", "another test"]

CodePudding user response:

Use sorted with key as str.startswith:

sorted(values, key=lambda x: not x.startswith(search_string))
# or without `not`
sorted(values, key=lambda x: x.startswith(search_string), reverse=True)

Output:

['test', 'teeest', 'another test', 'something']

CodePudding user response:

You can filter result twice, once for items that start with search_string, and another with those that do not:

[i for i in result if i.startswith(search_string)]   [i for i in result if not i.startswith(search_string)]

CodePudding user response:

Generally if you wants to sort based on where the search string is found, you can use str.index() to record where the search string starts, and then sort by these positions.

values = [ "another test", "test", "something", "teeest"]
search_string="te"
l = [ ((v.index(search_string), i), v) for i, v in enumerate(values) if search_string in v ]
l.sort()
_, result = zip(*l)
  • Related