I was wondering if someone could tell me the pythonic way to check out the following.
I have a 6 bit binary number and want to check with its decimal values. Using mathematical function is one way but still it would require that I write around 2**6 if constructs.
So I wanted to know if there's an easier statement to write it.
Also assume that lets say it's not binary then what's the better way to check for 2**6 values in python.
if(a==1):
....
else:
开发者_如何转开发 if(a==2)
.....
One way is saving it in a list and checking it with the indexes but still that would require that many if-else I guess.....
Thanks ....
Use a dictionary mapping values into outcomes (which can be functions in Python).
For example:
d = {}
d[0] = ....
d[1] = ....
d[2] = ....
outcome = d[a]
Naturally, how this works depends on your ....
, but this construct can be very flexible. The most important feature of this approach is that this dictionary can be populated programmatically, and you don't need to write a lot of manual assignments. It's of course also much more efficient than going over many values with nested if
statements (or elsif
)
To add to the responses of the others, you should read about the recommended Python style in PEP 8.
With your if
version, the brackets are undesirable and spacing is desirable:
if a == 1:
pass
elif a == 2:
pass
elif a == 3:
pass
else:
pass
I would use a decorator to map into a dictionary based dispatch:
_dispatch_table = {}
def dispatch_on(*values):
def dec(f):
_dispatch_table.update((v, f) for v in values)
return f
return dec
@dispatch_on(0, 2, 47)
def one():
foo()
bar()
@dispatch_on(2, 23, 89)
def two():
bar()
baz()
x = some_number
_dispatch_table[x]()
Personally I prefer a if/elif if I am understanding your ...
so your:
if(a==1):
....
else:
if(a==2)
.....
Becomes this if you use if elif
ladder:
if a==1:
....
elif a==2:
.....
else:
default
You can also use Python's version of a conditional expression for simple ladders:
def one():
print("option 1 it is\n")
def two():
print("option 2 it is\n")
def three():
print("not one or two\n")
one() if a==1 else two() if a==2 else three()
Or even dictionaries:
def one():
print("option 1 it is\n")
def two():
print("option 2 it is\n")
def three():
print("not one or two\n")
options = {1:one,
2:two,
3:three,
}
options[2]()
There is a great discussion on Python forms of switch-case in this SO post.
Based on the somewhat vague information in the question and what I've been able to gather from the OP's comments, here's my guess:
def func1(): pass
def func2(): pass
def func3(): pass
# ...
def func62(): pass
def func63(): pass
if 0 < a < 64:
globals()['func'+str(a)]()
else:
print 'a is out of range'
精彩评论