Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find The Best Match In List of string

I have

target = "dexter.new.blood.S01EP07.somerandomstring.mkv"

I managed to get only the name using split('.')
to be

target = "dexternewblood"

and

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

list = ['Dexter - Eighth Season (2013)', 'Dexter - Seventh Season  (2012)', 'Dexter - Fourth Season (2009)', 'Dexter - Third Season (2008)', 'Dexter - Sixth Season (2011)', 'Dexter - Fifth Season (2010)', 'Dexter: New Blood - First Season (2021)', 'Dexter - First Season (2006)', 'Dexter - Second Season (2007)']

I did the same thing to end up with:

list = ['Dexter ', 'Dexter ', 'Dexter ', 'Dexter ', 'Dexter ', 'Dexter ', 'Dexter: New Blood ', 'Dexter ', 'Dexter ']

I wanna get the best match which is "Dexter: New Blood"
if you can add way for getting index as well

>Solution :

From this similar post you can use SequenceMatcher from difflib built-in module:

from difflib import SequenceMatcher

target = "dexternewblood"
lst = ['Dexter ', 'Dexter ', 'Dexter ', 'Dexter ', 'Dexter ', 'Dexter ', 'Dexter: New Blood ', 'Dexter ', 'Dexter ']

a = [SequenceMatcher(None, i, target).ratio() for i in lst]

index = a.index(max(a)) # 6
match = lst[index] # 'Dexter: New Blood '
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading