0

How can I shorten this condition pattern;

if xconditon == "a text":
 Avariable = Yvariable

elif xcondition == "b text":
 Bvariable = Yvariable

elif xcondition == "c text":
 Cvariable = Yvariable

condition goes on like this, there is a pattern so I am searching for ways to shorten this code.

I'm looking for best way to reduce the code clutter, also improving the performance, looked for Python equivalent C++ auto, thought of using 2D lists but using dictionary seems better.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 1
    I can't think of an easy way to simplify it. Maybe you shouldn't use separate variables, use a dictionary whose key is the value of `xcondition` – Barmar Sep 01 '22 at 19:19
  • It sounds like you are creating variable variables. You should take a look at answers to this [question](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables) – quamrana Sep 01 '22 at 19:19

2 Answers2

3

Don't use different variables, use a dictionary.

mydict[xcondition] = Yvariable
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

You could loop through the list of conditions and their corresponding variable names if you really have a lot of them, for just three it doesnt make sense though. I made an example:

list = [
"a":{"letter":"a","condition":"conditionA", variable:"variableA"}
"b":{"letter":"b","condition":"conditionB", variable:"variableB"}
]

for i in list:
    if conditionX == i["condition"]:
        list["letter"]["variable"] = variableX