2011-10-13 55 views
1

我有这段代码。缩短if语句的序列

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 

我可以使这段代码更加紧凑吗?你会如何写得更好?

谢谢

回答

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 
+0

如果您不担心必须调用randrange和额外的开销,您也可以将randrange(101,len(list)-1)'作为字典的成员'' len即使当c!='r' – Kevin

+0

@Kevin:Thta会导致每个访问与'r'获得相同的数字。在每次调用时创建字典都没有什么不同,但需要在函数中定义字典(与其他地方相反,比如在配置文件中,或者从某些其他输入以编程方式)。这也是没有必要的,会有点浪费。 – delnan

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 
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) 
+0

它有非英文名字。我不得不重新命名它。 – xralf