缩短if语句的顺序

时间:2011-10-13 17:26:27

标签: python coding-style if-statement

我有这段代码。

c = getch()
if c == "r":                                                                   
  return randrange(101, len(mylist) - 1) 
if c == "u":                                                        
  return 100               
if c == "b":      
  return -2                
if c == "w":    
  return -3                
if c == "m":
  return -4                
if c == "d":
  return -5                
if c == "e":
  return -6                
if c == "k":
  return -7
if c == "g":
  return -8
if c == "p":
  return -9
if c == "o":
  right = center - 1       
else:                      
  left = center + 1

我可以将此代码段更紧凑吗?你会怎么写得更好?

谢谢

3 个答案:

答案 0 :(得分:8)

您可以使用字典:

# Special case.
if c == "r":                                                                   
    return randrange(101, len(list) - 1) 

# This is constant. It could be generated once at program start.
d = { 'u' : 100, ...., 'p' : -9 }

# This covers the majority of the cases.
if c in d:
    return d[c]

# Some more special cases.
if c == "o":
   right = center - 1       
else:                      
   left = center + 1

答案 1 :(得分:2)

我同意字典是要走的路。 Mark的答案问题是每个函数调用都会重建字典。解决方法是在函数外定义字典:

def foo():
    c = getch()
    if c in foo.mydict:
        return foo.mydict[c]
    else:
        # TODO: special cases

foo.mydict = {'u':100, ... , 'p':-9}

# foo is now ready to use

答案 2 :(得分:1)

您应该强烈考虑将list变量重命名为尚未使用的变量。

...
c=getch()
if c=="r":
    return randrange(101, len(mylist) - 1)

return dict(u=100, b=-2, w=-3, m=-4, d=-5, e=-6, k=-7, g=-8, p=-9, o=center-1).get(c, center+1)