【问题标题】:Shorten sequence of if statements缩短 if 语句的序列
【发布时间】:2011-10-13 17:26:27
【问题描述】:

我有这个代码。

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

我可以让这段代码 sn-p 更紧凑吗?怎么写比较好?

谢谢

【问题讨论】:

    标签: python coding-style if-statement


    【解决方案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
    

    【讨论】:

    • 您也可以将'r': randrange(101, len(list) -1) 作为字典的成员,如果您不担心即使在 c != 'r' 时也必须调用 randrange 和 len 的额外开销
    • @Kevin:这会导致每次访问'r' 获得相同的号码。在每次调用时创建字典时没有区别,但这需要在函数中定义字典(而不是......其他任何地方,如在配置文件中或以编程方式从其他输入)。这也是不必要的,会有点浪费。
    【解决方案2】:

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

    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
    

    【讨论】:

      【解决方案3】:

      您应该强烈考虑将您的 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)
      

      【讨论】:

      • 它有非英文名称。我不得不重命名它。
      猜你喜欢
      • 2012-07-05
      • 1970-01-01
      • 1970-01-01
      • 2018-08-19
      • 1970-01-01
      • 1970-01-01
      • 2016-03-26
      • 1970-01-01
      • 2012-04-06
      相关资源
      最近更新 更多