【问题标题】:Incrementing different variables via the ternary operator in a for loop在 for 循环中通过三元运算符递增不同的变量
【发布时间】:2018-03-19 11:55:17
【问题描述】:

我正在尝试在我的 for 循环中根据测试添加到不同的变量:

for i in range(alist.__len__()):
        if alist[i] is not blist[i]:
            ascore +=1 if alist[i] > blist[i] else bscore+=1
    print(ascore,bscore)

此代码不起作用。我所理解的情况是 if 条件不适用于整个赋值(我们增加 ascore if 条件),而是适用于我的值 1(我们将 ascore 增加 1 if 条件)。我更喜欢与第一个类似的功能。有什么我可以在这里做的吗?我知道如果 elsif 可以轻松解决这个特定问题,只需将其分解为,但我对三元运算符(单行条件)在 python 中的工作方式更感兴趣。谢谢!

【问题讨论】:

  • 赋值不是 Python 中的表达式(与 C/C++ 不同),因此您不能在此处使用三元运算符(它仅适用于表达式)。

标签: python increment ternary


【解决方案1】:

没有。不幸的是,您不能使用三元运算符。顾名思义,它是一个运算符,所以左右两边都必须是表达式。但是,与许多其他语言不同,Python assignments are statements,因此它们不能用于代替表达式。

正如您正确指出的那样,解决方案是使用正常的条件语句:

for i in range(len(list)):
        if alist[i] is not blist[i]:
            if alist[i] > blist[i]:
                ascore +=1 
            else:
                bscore +=1
    print(ascore, bscore)

【讨论】:

    【解决方案2】:

    如果你不坚持使用augmented assignmentmeng,你可以这样做:

    ascore, bscore = (ascore + 1, bscore) if alist[i] > blist[i] else (ascore, bscore + 1)
    

    感谢 ShadowRanger 指出我的错误(我错过了括号)。

    【讨论】:

    • 您的运算符优先级错误。您刚刚尝试将三个-tuple 分配给两个元素;保证ValueError。您想要:ascore, bscore = (ascore+1, bscore) if alist[i] > blist[i] else (ascore, bscore+1),但您实际上写道:ascore, bscore = ascore+1, (bscore if alist[i] > blist[i] else ascore), bscore+1
    【解决方案3】:

    如果您只需要增加两个变量 - 您可以通过字典来完成,使用以下代码:

    scores = {
        True: 0,   # ascore
        False: 0   # bscore
    }
    
    for i in range(len(alist)):
        if alist[i] is not blist[i]:
            scores[alist[i] > blist[i]] += 1
    
    print(scores)
    

    或相同,但更清楚:

    scores = {
        'ascore': 0,
        'bscore': 0
    }
    
    for i in range(len(alist)):
        if alist[i] is not blist[i]:
            scores['ascore' if alist[i] > blist[i] else 'bscore'] += 1
    
    print(scores)
    

    【讨论】:

      【解决方案4】:

      您还应该确保使用 != 和正常的 if 语句

      for i in range(len(alist)):
          if alist[i]!=blist[i]:
              if alist[i]>blist[i]:
                  ascore+=1
              else:
                  bscore+=1
          print(ascore,bscore)
      

      【讨论】:

      • is 将返回 True 如果两个变量指向同一个对象,== 如果变量引用的对象相等。这个运算符有不同的用途
      猜你喜欢
      • 2013-01-12
      • 2013-02-20
      • 1970-01-01
      • 2017-08-21
      • 2011-10-15
      • 1970-01-01
      • 2020-01-21
      • 1970-01-01
      • 2016-10-14
      相关资源
      最近更新 更多