TypeError:'int'对象不支持项目分配Python

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了TypeError:'int'对象不支持项目分配Python相关的知识,希望对你有一定的参考价值。

[谁能告诉我为什么我在Python 2.7中不断收到此错误,请参见下面的错误标记。预先感谢!

我必须编写一个程序来计算每人的硬币数量并弄清它们的总数

TotalPeople = int(raw_input("Enter the number of people "))
Loop = 0
DC2 = 0
DC1 = 0
C50 = 0
C25 = 0 
C10 = 0
C5 = 0 
C2 = 0 
TVC = 0.0
i = 1

while i != TotalPeople:
    DC2[i] = raw_input("How many 2 dollar coins?")     // ERROR for this line
    DC1[i] = raw_input("How many 1 dollar coins?")
    C50[i] = raw_input("How many 50 cent coins?")
    C25[i] = raw_input("How many 25 cent coins?")
    C10[i] = raw_input("How many 10 cent coins?")
    C5[i] = raw_input("How many 5 cent coins?")
    C2[i] = raw_input("How many 2 cent coins?")
    Total =  (DC2[i] *2) + (DC1[i] * 1) + (C50[i] * 0.50) + (C25[i] * 0.25) + (C10[i] * 0.10) + (C5[i] * 0.05) + (C2[i] * 0.02)
    print "The total is " + Total

iw = 1
while iw != TotalPeople:
    TVC = TVC + (DC2[iw] * 2)
    TVC = TVC + (DC1[iw] * 1) 
    TVC = TVC + (C50[iw] * 0.50) 
    TVC = TVC + (C25[iw] * 0.25) 
    TVC = TVC + (C10[iw] * 0.10) 
    TVC = TVC + (C5[iw] *  0.05) 
    TVC = TVC + (C2[iw] * 0.02)

print("The total value is CAD $" + str(TVC) + " for " + str(TotalPeople) +  " people") 
答案

您已将DC声明为整数,但在此行中:

DC2[i] = raw_input("How many 2 dollar coins?")

(以及前面所有连续的行),您正在处理它,就好像它是可定标对象一样。我认为您想要的是摆脱while循环内正在执行的所有索引分配。

DC2 = raw_input("How many 2 dollar coins?") 
DC1 = raw_input("How many 1 dollar coins?")
C50 = raw_input("How many 50 cent coins?")
C25 = raw_input("How many 25 cent coins?")
C10 = raw_input("How many 10 cent coins?")
C5 = raw_input("How many 5 cent coins?")
C2 = raw_input("How many 2 cent coins?")
另一答案

DC2是整数。您正在尝试为其分配它,就像它是list(带有索引)一样。那是行不通的。

以上是关于TypeError:'int'对象不支持项目分配Python的主要内容,如果未能解决你的问题,请参考以下文章

创建图像的缩略图失败,并出现TypeError:'int'对象不可下标

PYTHON,Midpoint方法,TypeError:'float'对象不能解释为整数

TypeError:当我尝试在parse.parse_args()中传递三个参数时,'int'对象不可订阅

“TypeError:'int'对象在2D,基于文本的Map Generator中是不可订阅的”

lambda and TypeError:'模块'对象不可调用[重复]

Python : TypeError: 'int' object is not iterable