繁体   English   中英

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

[英]TypeError: 'int' object does not support item assignment - new to Python

尝试在书中做一些问题,但我仍然坚持使用数组。 我收到此错误:

count[i] = x
TypeError: 'int' object does not support item assignment

我的代码:

import pylab
count = 0

for i in range (0,6):
    x = 180
    while x < 300:
        count[i] = x
        x = x + 20
        print count

基本上,我需要使用循环来存储增加的值,直到它们在数组中达到300。 我不确定为什么会收到该错误。

我可能措辞很差。 我需要使用循环来制作6个值(从200、220、240 ...到300),并将它们存储在数组中。

count是一个整数。 整数没有索引,只有列表或元组(或基于它们的对象)有索引。

您要使用列表,然后将值附加到它:

count = []
for i in range (0,6):
    x = 180
    while x < 300:
        count.append(x)
        x = x + 20
        print count

您已将count定义为一个int数,并且如错误所示( 'int' object does not support item assignment ),您需要一个列表,:

count = []

并使用append()函数将数字附加到列表中:

for i in range (0,6):
    x = 180
    while x < 300:
        count.append(x)
        x = x + 20
        print count

您不需要while循环,可以将范围与开始,停止,步骤一起使用:

count = []
for i in xrange (6):
    for x in  xrange(180,300,20):
        count.append(x)
        print count

或结合使用范围:

count = []
for i in xrange(6):
    count.extend(range(180,300,20))

或者简单地:

 count range(180,300,20) * 6 `

使用字典

count = {}

for i in range (0,6):
    x = 180
    while x < 300:
        count[i] = x
        x = x + 20
        print count

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM