【问题标题】:python switch statement doesn't workpython switch语句不起作用
【发布时间】:2012-05-07 06:07:52
【问题描述】:

我找到了一个实现 switch 语句的函数 -->

File = open('/file.txt','r')

    String = File.readline()
    String = str(String)
    print String 

    for case in switch(String):
        if case("Head"):
            print "test successed"
            break
        if case("Small"):
            print String
            break
        if case("Big"):
            print String
            break  
        if case():
            print String 
            break 

当我打印它时的字符串值是 Head,但 switch 语句总是转到最后一种情况.. 该函数显然工作正常,因为当我用 v = "Head" 更改字符串时它工作了!!!

知道出了什么问题吗?

开关功能 -->

class switch(object):
 def __init__(self, value):
    self.value = value
    self.fall = False

 def __iter__(self):
    """Return the match method once, then stop"""
    yield self.match
    raise StopIteration

 def match(self, *args):
    """Indicate whether or not to enter a case suite"""
    if self.fall or not args:
        return True
    elif self.value in args: # changed for v1.5, see below
        self.fall = True
        return True
    else:
        return False

【问题讨论】:

  • 你应该链接caseswitch对象/函数的实现,否则你在问一个没人能回答的问题。
  • 你把这个switch函数放在哪里了?你能指出它的来源吗?
  • 我添加了函数的实现
  • 你为什么要这样做?您正在生成完全非pythonic的代码。满足于if string == 'Head':elif string == 'Small':等。
  • @ChrisMorgan - 更好的是使用字典:P

标签: python file-io switch-statement


【解决方案1】:

请永远不要编写这样的代码。以适当的 Python 风格进行。 更容易阅读。任何遇到这种“开关”混乱用法的人可能会发自内心地诅咒你。

with open('/file.txt', 'r') as fp:
    line = fp.readline().rstrip('\n')
    print line

if line == 'Head':
    print "test successed"
elif line == 'Small':
    print line
elif line == 'Big':
    print line
else:
    print line

至于失败的原因,readline() 调用很可能包含尾随换行符和 'Head' != 'Head\n'

【讨论】:

  • 谢谢,我会在 switch 语句中使用 (line = fp.readline().rstrip('\n'))找到第一个比较,因为在我的代码中我正在比较大量数据..我认为 if else 语句遍历了 if(s) 的整个列表,这不适用于我的需要...再次感谢您
  • @user573014:它没有if, elif, elif, elif, else... 它的处理效率很高。 switch 不是这样的——它会非常效率低下。
  • 使用 fp.readline().rstrip() 因为换行符可能是 "\r\n" 所以剥离 \n 将离开 \r
  • @EsbenSkovPedersen:我想在模式中添加U,但最终变得懒惰。可能不是一个好计划。
【解决方案2】:

.readline() 返回整行,包括换行符。

您需要.strip() 您的字符串,或与'Head\n' 等进行比较。

另外,关于样式,大写变量名在 python 中并不是真正的东西。

【讨论】:

    【解决方案3】:

    编辑:我知道这不是 Pythonic,但这是一个有趣的练习。

    这是在 OP 添加实现之前 - 这是我的看法。 它

    • raises 在没有定义大小写时出现有意义的错误 -- 或者如果设置了 allow_fallthrough,则可以使用 for:else: 处理默认大小写
    • 允许默认情况出现在"switch" 套件中的任何位置

    .

    def switch(arg, allow_fallthrough = False):
        fail = False
        def switcher(*args):
            return (arg in args)
        def default_switcher(*args):
            return (not args)
        def fallthrough(*args):
            if not allow_fallthrough:
                raise ValueError("switch(%r) fell through" % arg)
        yield switcher
        yield default_switcher
        yield fallthrough
    
    def test():
        String = "Smallish"
    
        for case in switch(String):
            if case():
                print "default", String 
                break
            if case("Head"):
                print "Head GET"
                break
            if case("Small", "Smallish"):
                print "Small:", String
                break
            if case("Big"):
                print "Big:", String
                break  
        else: # Only ever reached with `allow_fallthrough`
            print "No case matched"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-08
      • 1970-01-01
      • 2014-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多