Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

dictionary - How to avoid very long if-elif-elif-else statements in Python function

Is there a smart way to shorten very long if-elif-elif-elif... statements?

Let's say I have a function like this:

def very_long_func():
  something = 'Audi'
  
  car = ['VW', 'Audi', 'BMW']
  drinks = ['Cola', 'Fanta', 'Pepsi']
  countries = ['France', 'Germany', 'Italy']
  
  if something in car:
    return {'type':'car brand'}
  elif something in drinks:
    return  {'type':'lemonade brand'}
  elif something in countries:
    return {'type':'country'}
  else:
    return {'type':'nothing found'}
  

very_long_func()
>>>> {'type': 'car brand'}

The actual function is much longer than the example. What would be the best way to write this function (not in terms of speed but in readability)

I was reading this, but I have trouble to apply it to my problem.

question from:https://stackoverflow.com/questions/66065777/how-to-avoid-very-long-if-elif-elif-else-statements-in-python-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can't hash lists as dictionary values. So go other way round. Create a mapping of type -> list. And initialize your output with the default type. This allows you to keep on adding new types to your mapping without changing any code.

def very_long_func():
  something = 'Audi'
  
  car = ['VW', 'Audi', 'BMW']
  drinks = ['Cola', 'Fanta', 'Pepsi']
  countries = ['France', 'Germany', 'Italy']
  
  out = {'type': 'nothing found'}  # If nothing matches
  mapping = {
      'car brand': car,
      'lemonade brand': drinks,
      'country': countries
    }
  for k,v in mapping.items() :
    if something in v:
      out['type'] = k    # update if match found
      break
  return out             # returns matched or default value

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...