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

What is the best way to search for a value in a list of list of strings?

I have the following lists of stings (series):

serie_1 = ['ABC1', 'ABC2', 'AFG9']
serie_2 = ['CX1', 'CX9', 'CXL']
serie_3 = ['HOM1', 'HOM65']

I have a string (as an input) and I want to check to which list it belongs to so that I output a different value. For example, if INPUT = ‘HOM112343’, then I need to output (log) "Alpha serie", if INPUT = ‘HOM65XL’ then I need to output "Home Design".

I have this and it’s working fine:

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

if any(ser in INPUT.upper() for ser in serie_1):
    return "Alpha serie"
if any(ser in INPUT.upper() for ser in serie_2):
    return "Casio Extreme"
if any(ser in INPUT.upper() for ser in serie_3):
    return "Home Design"

I’m wondering what’s the best approach to do this, and if there’s an alternative more efficient way to do it as my series (serie_4, _5, _6 …) are getting bigger overtime.

Thanks

>Solution :

Don’t use separate variables for the lists, put them in a dictionary. Then you can loop through the dictionary, and return the key when you find a match.

serie = {
    "Alpha serie": ['ABC1', 'ABC2', 'AFG9'],
    "Casio Extreme": ['CX1', 'CX9', 'CXL'],
    "Home Design": ['HOM1', 'HOM65']
}

INPUT = INPUT.upper()

for key, values in serie.items():
    if any(ser in INPUT for ser in values):
        return key
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