Python 类型错误:“int”对象不支持项目分配

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14805306/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:29:30  来源:igfitidea点击:

TypeError: 'int' object does not support item assignment

pythontypeerror

提问by Ris

Why do I get this error?

为什么我会收到这个错误?

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

Code:

代码:

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))

采纳答案by mgilson

You're passing an integer to your function as a. You then try to assign to it as: a[k] = ...but that doesn't work since ais a scalar...

您将一个整数作为a. 然后您尝试将其分配为: a[k] = ...但这不起作用,因为它a是一个标量......

It's the same thing as if you had tried:

这与您尝试过的事情相同:

50[42] = 7

That statement doesn't make much sense and python would yell at you the same way (presumably).

那句话没有多大意义,python 会以同样的方式对你大喊大叫(大概)。

Also, ++kisn't doing what you think it does -- it's parsed as (+(+(k)))-- i.e. the bytcode is just UNARY_POSITIVEtwice. What you actually want is something like k += 1

此外,++k没有做你认为它做的事情——它被解析为(+(+(k)))——即字节码只是UNARY_POSITIVE两次。你真正想要的是k += 1

Finally, be careful with statements like:

最后,请注意以下语句:

q = q / b

The parenthesis you use with print imply that you want to use this on python3.x at some point. but, x/ybehaves differently on python3.x than it does on python2.x. Looking at the algorithm, I'm guessing you want integer division(since you check q != 0which would be hard to satisfy with floats). If that's the case, you should consider using:

与 print 一起使用的括号暗示您希望在某个时候在 python3.x 上使用它。但是,x/y在 python3.x 上的行为与在 python2.x 上的行为不同。看看算法,我猜你想要整数除法(因为你检查q != 0哪个很难满足浮点数)。如果是这种情况,您应该考虑使用:

q = q // b

which performs integer division on both python2.x and python3.x.

它对 python2.x 和 python3.x 执行整数除法。