Python: Another look to switch-case block

Some code constructions like: a = 'first' if 1==2 \ else 'smoke' if 1==0 \ else 'spoke' if True == False \ else 'forth' if False \ else 'default' make me blub. What happens if conditions will be giant? Omg, it’s will looks terrible!

Root of solution is in a little tip: ['a', 'b'][1==2]

Here is it: a = ['first', 'smoke', 'spoke', 'forth', 'default'][[ 1==2, 1==0, True==False, False, True ].index(True)]

Pay attention to the following:
* only the first of True-conditions will be selected (thanks to method index);
* last (or default) value must be and always set to True, otherwise exception IndexError will be thrown when all conditions is False.

UPD:

Multiple selection: a = ['first', 'smoke', 'spoke', 'forth']; c = [1==2, 1==0, True==False, False]; a = [x for z,x in zip(c,a) if z] or ['default'];

or one-liner: a = [x for c,x in zip([1==2, 1==0, True==False, False], ['first', 'smoke', 'spoke', 'forth']) if c] or ['default'];

or [‘default’] mean that if no one is selected from condition-value list use the right side of the or.

Another case to make less code with string conditions: a = dict(First="apricot", Second="banana", Third="coconut").get(selectValue, "desert") As result you get “desert” (or None by default) if selectValue is none of keys in dict.

Leave a Reply

Your email address will not be published. Required fields are marked *