更好的写作风格为以下代码

时间:2010-11-18 07:11:28

标签: python

我想知道是否有人能告诉我pythonic的方法来检查以下内容。

我有一个6位二进制数,想要检查其十进制值。使用数学函数是一种方法,但是如果构造的话,我还需要写2 ** 6。

所以我想知道是否有一个更简单的陈述来写它。

还假设我们说它不是二进制的,那么在python中检查2 ** 6值的更好方法是什么。

if(a==1):
    ....
else:
    if(a==2)
.....

一种方法是将它保存在列表中并使用索引进行检查但仍然需要很多if-else我猜......

谢谢....

5 个答案:

答案 0 :(得分:4)

使用字典将值映射到结果(可以是Python中的函数)。

例如:

d = {}
d[0] = ....
d[1] = ....
d[2] = ....

outcome = d[a]

当然,这是如何工作取决于你的....,但这种结构可以非常灵活。此方法最重要的特性是可以通过编程方式填充此字典,并且您无需编写大量手动分配。它当然也比使用嵌套的if语句(或elsif

来覆盖许多值更有效率

答案 1 :(得分:2)

要添加其他人的回复,您应该阅读PEP 8中推荐的Python样式。

使用if版本时,方括号是不受欢迎的,并且需要间距:

if a == 1:
    pass
elif a == 2:
    pass
elif a == 3:
    pass
else:
    pass

答案 2 :(得分:0)

我会使用装饰器映射到基于字典的调度:

_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]()    

答案 3 :(得分:-1)

如果我理解你的...

,我个人更喜欢if / elif

所以你的:

if(a==1):
    ....
else:
    if(a==2)
.....

如果您使用if elif阶梯:

,请成为此项
if a==1:
    ....
elif a==2:
    .....
else:
    default

您还可以将Python的条件表达式用于简单梯子:

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()

甚至字典:

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]()

this SO post中有关于switch形式的Python形式的讨论很多。

答案 4 :(得分:-3)

基于问题中有些模糊的信息以及我从OP的评论中收集到的信息,这是我的猜测:

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'
相关问题