0

I'm new to python and I need some help on this part of my project. How can I simplify this?

 if x == 'C':
    if y == 1:
        z = 1
    if y == 2:
        z = 2
    if y == 3:
        z = 3
    if y == 4:
        z = 1
    if y == 5:
        z = 2
morax
  • 1
  • 1
    Looks like the dictionary datatype would work well for this. If you nest them, this whole tree could be simplified to `z = myspecialdictionary[x][y]`. – skrrgwasme Oct 25 '21 at 18:14
  • Or a match statement in Python 3.10+ – khelwood Oct 25 '21 at 18:14
  • you cant simplify it, but you could make it a dictionary. – Haha6733 Oct 25 '21 at 18:15
  • 1
    Does this answer your question? [Replacements for switch statement in Python?](https://stackoverflow.com/questions/60208/replacements-for-switch-statement-in-python) – mkrieger1 Oct 25 '21 at 18:26
  • The dictionary solution looks quite good, if you really stay on an if structure you should use `elif` instead only `if` – B.R. Oct 25 '21 at 18:38

3 Answers3

6

Using a dict as a switch statement:

switcher = {'C': {1: 1, 2: 2, 3: 3, 4: 1, 5: 2}, ...}

z = switcher[x][y]
Jab
  • 26,853
  • 21
  • 75
  • 114
  • 2
    please note: the program will crash (raise a `KeyError`) if the key is not found. you should consider using `switcher.get(x, {}).get(y, None)` instead – Kesslwovv Oct 25 '21 at 18:51
1

Taking into account the frequency of the resulting values, the condition can be set by the expression

if x == 'C' and 0 < y < 6:
    z = (y - 1) % 3 + 1
Алексей Р
  • 7,507
  • 2
  • 7
  • 18
  • Provided this is not a dummy example, you have a valid point. It is more explicit to compute an easy value rather than maintaining a (large) list of mapping. +1 – mozway Oct 25 '21 at 19:04
0

in this case you can just use list:

C = [None,1,2,3,1,2]
if x == 'C':
    z=C[y]
ncica
  • 7,015
  • 1
  • 15
  • 37