簡體   English   中英

嘗試在使用for的列表中查找元組時,為什么會出現“無法分配給運算符”錯誤?

[英]Why do I get a “Can't assign to operator” error when trying to find tuple in a list using for?

我正在為學校編寫一個戰艦程序,每個方格在list buttonList都有一個元組作為坐標。 現在,我試圖通過for (coordinates) in buttonList:使用for (coordinates) in buttonList:來更改列表中的元組for (coordinates) in buttonList:但是在for和第一個元組之間的空間中,我for (coordinates) in buttonList:收到“無法分配給運算符”錯誤。

for (j,l+n,zeichen), (j+o,l,zeichen), (j,l-s,zeichen), (j-w,l,zeichen) in buttonList:
    if zeichen == 0:
       buttonList[(j,l+n,0)]=buttonList[(j,l+n,1)]
       buttonList[(j+o,l,0)]=buttonList[(j+o,l,1)]
       buttonList[(j,l-s,0)]=buttonList[(j,l-s,1)]
       buttonList[(j-w,l,0)]=buttonList[(j-w,l,1)]

您正在for循環中分配給l+nj+olsjw

for (j,l+n,zeichen), (j+o,l,zeichen), (j,l-s,zeichen), (j-w,l,zeichen) in buttonList:
    #  ^^^            ^^^                ^^^            ^^^

您不能在for循環目標中使用表達式; 使用新的(希望有意義的)變量名。 為每個目標使用單獨的唯一目標。

鑒於您的分配似乎在buttonList上使用了元組鍵,並且for循環在同一個對象上,因此即使該對象被命名為buttonList ,您似乎buttonList嘗試操作字典

在這種情況下,您的for循環將遍歷各個元組鍵 ,而不是每次迭代包含四個元組。 您只需要使用:

for j, l, sign in buttonList:
    if sign == 0:
        buttonList[j, l, 0] = buttonList[j, l, 1]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM