2017-01-09 52 views
0

我想通過在數組中添加1到數組中的項目,如果金錢== 100,並且如果沒有添加1到另一個項目,則嘗試在python中執行三元運算。但是我一直在得到一個無效的語法錯誤。添加整數的Python三元運算符

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" 
+0

是否要在其他部分將'bills [1] + 1'添加到'bills [2]'中? – letmutx

回答

5

你不能把聲明表達+=(作業)是一個聲明。您只能在語句的特定部分內使用表達式(如分配的右側)。

可以在這裏使用條件表達式,但用它來接分配給哪些指標:

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

這工作,因爲在任務目標上[...]訂閱內的部分也需要一個表達式。

+0

非常好,謝謝! – Oxymoron88

+0

Gotcha非常感謝! –

+0

@EdoziéIzegbu:很高興有幫助!如果您覺得它對您有用,請隨時[接受我的回答](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)。 :-) –