0

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?

Chandler Bong
  • 461
  • 1
  • 3
  • 18
  • 8
    Use a Dictionary? – thefourtheye Sep 26 '22 at 09:11
  • 1
    `values = {'C': 'Capacitor', ...}` `[values[i] for i in some_list]`…? – deceze Sep 26 '22 at 09:13
  • 1
    Does this answer your question? [Most efficient way of making an if-elif-elif-else statement when the else is done the most?](https://stackoverflow.com/questions/17166074/most-efficient-way-of-making-an-if-elif-elif-else-statement-when-the-else-is-don) – buran Sep 26 '22 at 09:13

2 Answers2

1

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]}!")
Coşkun
  • 49
  • 5
0

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]
Emi OB
  • 2,814
  • 3
  • 13
  • 29