views:

584

answers:

3

I am trying to check each index in an 8 digit binary string. If it is '0' then it is 'OFF' otherwise its 'ON'. I'm wondering if there's a more concise way to write this code with a switch-like feature.

Thanks,

+21  A: 

"Why isn't there a switch or case statement in Python?"

Milen A. Radev
I embedded a snippet from your very good link, roll it back if you don't like it.
Dustin Getz
That doesn't have fall-through either.
dlamblin
In *theory* you could implement a one-liner with fall-through by using defaultdict: >>> from collections import defaultdict >>> functions = defaultdict(lambda : not_found, a=function_1, b=function_2)but probably not a good idea in practice, particularly if the fall-through case is common :)
Ned Deily
fall-through is a bad idea. good riddance.
joeforker
+8  A: 

No it doesn't. In the Python core language, one of the rules is to only have one way to do something. The switch is redundant to:

if x == 1:
    pass
elif x == 5:
    pass
elif x == 10:
    pass

(without the fall-through, of course).

The switch was originally introduced to cut down on the number of angle brackets needed to do do similar if blocks, however, with python there are no brackets anyways.

Soviut
==
Fragsworth
Anyone who thinks Python "only has one way to do something" is very confused.
Glenn Maynard
Fixed. I guess I could have claimed that it was python-esque pseudo-code, hehe.
Soviut
@Glenn Maynard: There may be more than one way to do it, but "There should be one -- and preferably only one -- **obvious** way to do it", per PEP 20 ("The Zen of Python").
Daniel Pryden
I believed `switch`'s purpose was to tell the compiler to build a jump table? (I know current compilers don't need this.)
Bastien Léonard
@Glenn do understand that while there are many redundant python modules, the actual core language has little in the way of redundant functionality.
Soviut
Although that way may not be obvious at first unless you're Dutch.
Stefano Borini
+4  A: 

Try this instead:

def on_function(*args, **kwargs):
    # do something

def off_function(*args, **kwargs):
    # do something

function_dict = { '0' : off_function, '1' : on_function }

for ch in binary_string:
   function_dict[ch]()

Or you could use a list comprehension or generator expression if your functions return values:

result_list = [function_dict[ch]() for ch in binary_string]
Jeff
This is really clever.
twneale