Home > Mobile >  Clean alternative needed for if elif else tree?
Clean alternative needed for if elif else tree?

Time:09-26

I have some code where a variable can have any of the following values:

["C", "D", "IC", "R", "T", "K"]

That tells the program what to give as an output. So if I take all the items of the list and loop throug it, then is will replace all the items with the needed output:

["Capacitor", "Diode", "IntigratedCircuit", "Resistor", "Transistor", "Relay"]

Current code looks like this:

if ComponentIdentifier == "C":
    print("{} is a Capacitor!".format(TypeComponent))
elif ComponentIdentifier == "D":
    print("{} is a Diode!".format(TypeComponent))
elif ComponentIdentifier == "IC":
    print("{} is an IC!".format(TypeComponent))
elif ComponentIdentifier == "R":
    print("{} is a Resistor!".format(TypeComponent))
elif ComponentIdentifier == "T":
    print("{} is a Transistor!".format(TypeComponent))

The way this is currently achieved is as follows: I have a long if-elif-else block that checks every answer and gives the needed value. But, preferably I would want something like this (Following code is not real):

if i in ["C", "D", "IC", ...]:
    ["C", "D", "IC", ...][i] to ["Capacitor", "Diode", ...]

Does anyone know how to make a long if-elif tree compact in python?

CodePudding user response:

You can use a dictionary instead of if-else block.

options = {
  "C": "Capacitor",
  "D": "Diode", 
  "IC": "IntigratedCircuit",
  "R": "Resistor", 
  "T": "Transistor",
  "K": "Relay",
}

and then

print(f"{ComponentIdentifier} is a {options[ComponentIdentifier]}!")

CodePudding user response:

Commenter Deceze and Thefourtheye figured it out.

Cleanest way in my case is using a dict

valueas = {'C': 'Capacitor', ...}
[valueas[i] for i in some_list]
  • Related