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?
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With