Edo*_*gbu 0 python conditional-operator python-3.x
我试图在python中进行三元运算,如果money == 100,则在数组中的项目中添加1,如果不是,则在另一个项目中添加1.但我继续得到无效的语法错误.
bills[2] += 1 if money == 100 else bills[1] += 1
^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)
这是代码.
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"
Run Code Online (Sandbox Code Playgroud)
你不能把语句放在表达式中.+=(转让)是一份声明.您只能在语句的特定部分内使用表达式(如赋值的右侧).
您可以在此处使用条件表达式,但使用它来选择要分配的索引:
bills[2 if money == 100 else 1] += 1
Run Code Online (Sandbox Code Playgroud)
这是有效的,因为[...]赋值目标中的订阅内的部分也采用表达式.
| 归档时间: |
|
| 查看次数: |
262 次 |
| 最近记录: |