lundi 26 février 2018

Optimize long if statement in Python

I have a if statement inside a loop that sets a variable to a specific country name if it matches the condition, that is, if the parameter contains the country name.

The parameters are a list of paths that contain a country name in different positions, i.e. C:\\some\\path\\text_country_text.xlsx or C:\\some\\path\\text_text_country_text.xlsx

The if statement is pretty long at the moment because it checks a rather long list of countries. The code I wrote works but it does not look really optimized. Is there a shorter way to do this?

def my_function(*args): 
    for country in args:
        if "Australia" in country:
            country_name = "Australia"
        elif "Austria" in country:
            country_name = "Austria"
        # etc. for many countries

Aucun commentaire:

Enregistrer un commentaire