类型错误:“int"对象不支持项目分配 [英] TypeError: 'int' object does not support item assignment

查看:44
本文介绍了类型错误:“int"对象不支持项目分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么会出现此错误?

    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 是标量...

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 a is a scalar...

这就像你尝试过的一样:

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

50[42] = 7

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

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

另外,++k 并没有像你想象的那样做——它被解析为 (+(+(k)))——即字节码只是 UNARY_POSITIVE 两次.你真正想要的是类似于 k += 1

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

最后,请注意以下语句:

Finally, be careful with statements like:

q = q / b

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

The parenthesis you use with print imply that you want to use this on python3.x at some point. but, x/y behaves 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 != 0 which would be hard to satisfy with floats). If that's the case, you should consider using:

q = q // b

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

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

这篇关于类型错误:“int"对象不支持项目分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆