Skip to main content
 首页 » 编程设计

python之缩短 if 语句的序列

2025年05月04日14JustinYoung

我有这个代码。

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 

我可以让这个代码片段更紧凑吗?怎么写比较好?

谢谢

请您参考如下方法:

你可以使用字典:

# 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