[英]TypeError: 'int' object does not support item assignment
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))
You're passing an integer to your function as a
. 你传递一个整数,以你的函数作为
a
。 You then try to assign to it as: a[k] = ...
but that doesn't work since a
is a scalar... 然后,您尝试将其分配为:
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, ++k
isn't doing what you think it does -- it's parsed as (+(+(k)))
-- ie the bytcode is just UNARY_POSITIVE
twice. 另外,
++k
并没有按照您的想法去做-被解析为(+(+(k)))
,即字节码只是两次UNARY_POSITIVE
。 What you actually want is something like k += 1
您实际想要的是类似
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. 与print一起使用的括号表示您想在某个时候在python3.x上使用它。 but,
x/y
behaves differently on python3.x than it does on python2.x. 但是,
x/y
在python3.x上的行为不同于在python2.x上的行为。 Looking at the algorithm, I'm guessing you want integer division (since you check q != 0
which would be hard to satisfy with floats). 看一下算法,我猜你想要整数除法 (因为检查
q != 0
,这对于浮点数很难满足)。 If that's the case, you should consider using: 如果是这样,您应该考虑使用:
q = q // b
which performs integer division on both python2.x and python3.x. 在python2.x和python3.x上执行整数除法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.