Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reduced if/else block

Tags:

python

I'm trying to assign a value to a variable according to some input. This is what I currently do:

if a == 1:
    var = 'some_value'
elif a == 2:
    var = 'another_one'
elif a == 3:
    var = 'text_string'
elif a == 4:
    var = 'one_more'
elif a == 5:
    var = 'final_str'

So basically it maps a given value to var according to the value of a. Could this be pythonified somehow?

like image 488
Gabriel Avatar asked Sep 25 '26 06:09

Gabriel


2 Answers

You can use a dictionary:

var_map = {1: 'foo', 2: 'bar', 10: 'spam'}
var = var_map[a]

If a is a sequential integer, you can use a list too:

var_map = [None, 'some_value', 'another_one', 'text_string', 'one_more', 'final_str']
var = var_map[a]

Here var_map[0] is set to None to keep the sequence map simple.

like image 61
Martijn Pieters Avatar answered Sep 27 '26 19:09

Martijn Pieters


You probably want to use a dictionary if you're going to run this if block multiple times.

d = {
      '1':'value_1',
      '2':'value_2',
      '3':'value_3',
      '4':'value_4',
      '5':'value_5'
    }

var = d[a]
like image 30
Hoopdady Avatar answered Sep 27 '26 21:09

Hoopdady



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!