简体   繁体   中英

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, ie 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

Assuming you don't know exactly where the country name is within your country string (so you can't use slicing or a regex to extract the relevant portion), you could adapt your approach to take a list of countries, and then use a generator expression with next() to extract the country name:

next((c_name for c_name in countries if c_name in country), 'Unknown')

Examples:

>>> countries = ['Australia', 'Austria']
>>> country = '#Austrian_man#'
>>> next((c_name for c_name in countries if c_name in country), 'Unknown')
'Austria'
>>> country = '#AustrTYPO_man#'
>>> next((c_name for c_name in countries if c_name in country), 'Unknown')
'Unknown'

You could do: Countries = [ all countries] Code:

for country in args:
  for i in Countries:
        if i in country:
          country_name = i

Just for the fun of it, and to show the power of set s, it is possible to solve this with only one for loop and a set.intersection() call:

def my_function(*args):
    countries = set(['Austria', 'Australia', 'Brazil', 'Denmark'])
    for country_name in countries.intersection(args):
        print(country_name)

Thus, the loop will only loop over countries that are both among the input arguments and in the predefined countries set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM