簡體   English   中英

TypeError:“ int”對象不支持項目分配

[英]TypeError: 'int' object does not support item assignment

為什么會出現此錯誤?

    a[k] = q % b
 TypeError: 'int' object does not support item assignment

碼:

def algorithmone(n,b,a):
     assert(b > 1)
     q = n
     k = 0
     while q != 0:
        a[k] = q % b
        q = q / b
        ++k

     return k

print (algorithmone(5,233,676))
print (algorithmone(11,233,676))
print (algorithmone(3,1001,94))
print (algorithmone(111,1201,121))

你傳遞一個整數,以你的函數作為a 然后,您嘗試將其分配為: a[k] = ...但這不起作用,因為a是標量...

就像您嘗試過的一樣:

50[42] = 7

該語句沒有多大意義,並且python會以相同的方式對您大喊大叫(大概)。

另外, ++k並沒有按照您的想法去做-被解析為(+(+(k))) ,即字節碼只是兩次UNARY_POSITIVE 您實際想要的是類似k += 1

最后,請注意以下語句:

q = q / b

與print一起使用的括號表示您想在某個時候在python3.x上使用它。 但是, x/y在python3.x上的行為不同於在python2.x上的行為。 看一下算法,我猜你想要整數除法 (因為檢查q != 0 ,這對於浮點數很難滿足)。 如果是這樣,您應該考慮使用:

q = q // b

在python2.x和python3.x上執行整數除法。

暫無
暫無

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

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