【问题标题】:Python Ternary Operator adding integersPython三元运算符添加整数
【发布时间】:2017-05-23 18:51:11
【问题描述】:

我正在尝试在 python 中进行三元运算,如果 money == 100 则将 1 添加到数组中的项目,如果没有,则将 1 添加到另一个项目。但我不断收到无效的语法错误。

 bills[2] += 1 if money == 100 else bills[1] += 1
                                             ^
SyntaxError: invalid syntax

这是代码。

def tickets(people):
change =0 
bills = [0,0,0]
for i,money in enumerate(people):
    if money == 25:
        change += 25
        bills[0] += 1
        str = "This is the %d th person with %d money" % (i,money)
        print(str)

    else:
        bills[2] += 1 if money == 100 else bills[1] += 1
        change -= (money -25)
        str = "This is the %d th person with %d money" % (i,money)
        print(str)
        print("change is %d" % change)

if change < 0:
    return "NO"
else:
    return "YES"

【问题讨论】:

  • 你想在else部分将bills[1] + 1添加到bills[2]吗?

标签: python python-3.x conditional-operator


【解决方案1】:

您不能将语句放在表达式中。 +=(赋值)是一个声明。您只能在语句的特定部分(如赋值的右侧)中使用表达式。

可以在此处使用条件表达式,但使用它来选择要分配给的索引:

bills[2 if money == 100 else 1] += 1

之所以有效,是因为分配目标中[...] 订阅内的部分也采用表达式。

【讨论】:

  • @EdoziéIzegbu:很高兴能帮上忙!如果您觉得它对您有用,请随时 accept my answer。 :-)
猜你喜欢
  • 2015-07-13
  • 1970-01-01
  • 2022-01-05
  • 1970-01-01
  • 2012-11-09
  • 2012-07-25
  • 1970-01-01
  • 1970-01-01
  • 2011-05-05
相关资源
最近更新 更多