【问题标题】:Assignments in conditions条件中的分配
【发布时间】:2014-10-22 17:13:12
【问题描述】:

在类 C 语言中,我们可以编写这样的循环:

while ( a = func(x) ){
    // use a
}

在 Python 中有什么语法可以做同样的事情吗?

【问题讨论】:

    标签: python syntax variable-assignment


    【解决方案1】:

    没有直接的等价物,因为 Python 中的 assignments are statements,而不是 C 中的表达式。

    相反,您可以这样做:

    a = func(x)      # Assign a
    while a:         # Loop while a is True
        # use a
        a = func(x)  # Re-evaluate a
    

    或者这个:

    while True:      # Loop continuously
        a = func(x)  # Assign a
        if not a:    # Check if a is True
            break    # Break if not
        # use a
    

    第一个解决方案代码更少,但我个人更喜欢第二个解决方案,因为它可以防止您重复 a = func(x) 行。

    【讨论】:

      【解决方案2】:

      没有 python 没有这个,因为你对像这样的错误敞开心扉

      if usr = 'adminsitrator':
          # do some action only administrators can do
      

      你真正的意思是==而不是=

      【讨论】:

        【解决方案3】:

        Python 不允许用赋值代替布尔表达式。这样做的“pythonic”方法是:

        def func(x):
            if goodStuff:
                return somethingTruthy
            else:
                return somethingFalsey
        
        a = func(x)
        while a:
            # use a
            a = func(x)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-10-17
          • 1970-01-01
          • 2017-11-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多