Marco Fucci
Marco Fucci

Reputation: 1854

Filter a list and order items by relevance

I have a list of strings:

my_list = ['Paul', 'Robinson', 'Hismith', 'Smith']

I need to filter it and order the results by relevance:

> filter_list(my_list, 'smith')
> ['Smith', 'Hismith']
> 
> filter_list(my_list, 'paul')
> ['Paul']

My list is small and it would be nice if I could use as less logic/libraries as possible.

How would you do this?

Thanks!

Upvotes: 2

Views: 627

Answers (2)

Jon Clements
Jon Clements

Reputation: 142216

Try something like the following (you may want to tweak the cutoff= option though):

import difflib

my_list = ['Paul', 'Robinson', 'Hismith', 'Smith']
print difflib.get_close_matches('Paul', my_list)
# ['Paul']
print difflib.get_close_matches('Smith', my_list)
# ['Hismith', 'Smith']

Upvotes: 7

eumiro
eumiro

Reputation: 213015

Difficult to tell, what is the "relevance". In my answer I accept only if the sought word is within the element and sort the results by their length (good chances that 100% matches will appear first):

def filter_list(li, word):
    return sorted((elem for elem in li if word.lower() in elem.lower()), key=len)

Upvotes: 6

Related Questions