[英]TypeError: 'int' object does not support item assignment - new to Python
Trying to do some some questions in a book yet I'm stuck with my arrays. 尝试在书中做一些问题,但我仍然坚持使用数组。 I get this error: 我收到此错误:
count[i] = x
TypeError: 'int' object does not support item assignment
My code: 我的代码:
import pylab
count = 0
for i in range (0,6):
x = 180
while x < 300:
count[i] = x
x = x + 20
print count
Basically I need to use a loop to store values which increase until they hit 300 in an array. 基本上,我需要使用循环来存储增加的值,直到它们在数组中达到300。 I'm not sure why I'm getting that error. 我不确定为什么会收到该错误。
I might have worded this poorly. 我可能措辞很差。 I need to use a loop to make 6 values, from 200, 220, 240... to 300, and store them in an array. 我需要使用循环来制作6个值(从200、220、240 ...到300),并将它们存储在数组中。
count
is an integer. count
是一个整数。 Integers don't have indexes, only lists or tuples (or objects based on them) do. 整数没有索引,只有列表或元组(或基于它们的对象)有索引。
You want to use a list, and then append values to it: 您要使用列表,然后将值附加到它:
count = []
for i in range (0,6):
x = 180
while x < 300:
count.append(x)
x = x + 20
print count
You have defined count
as an int
number and as the error says ( 'int' object does not support item assignment
) you need a list instead , : 您已将count
定义为一个int
数,并且如错误所示( 'int' object does not support item assignment
),您需要一个列表,:
count = []
and use append()
function to append the numbers to your list : 并使用append()
函数将数字附加到列表中:
for i in range (0,6):
x = 180
while x < 300:
count.append(x)
x = x + 20
print count
You don't need the while loop, you can use range with a start,stop,step: 您不需要while循环,可以将范围与开始,停止,步骤一起使用:
count = []
for i in xrange (6):
for x in xrange(180,300,20):
count.append(x)
print count
Or use range with extend: 或结合使用范围:
count = []
for i in xrange(6):
count.extend(range(180,300,20))
Or simply: 或者简单地:
count range(180,300,20) * 6 `
Use dictionary 使用字典
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.