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

Advertisements

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:

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

Leave a ReplyCancel reply