python 报错TypeError: 'range' object does not support item assignment,解决方法

1. 例子如下:

from math import sqrt
if __name__ == '__main__':
    N = 100
    a = range(0,N)
    for i in range(2,int(sqrt(N))):
        for j in range(i + 1,N):
            if (a[i] != 0) and (a[j] != 0):
                if a[j] % a[i] == 0:
                        a[j]= 0

    for i in range(2,N):
        if a[i] != 0:
            print ("%5d" % a[i])
            if (i - 2) % 10 == 0:
                print         

执行后报错:TypeError: ‘range’ object does not support item assignment

2 .报错原因如下:

尝试使用range()
创建整数列表(导致“TypeError: ‘range’ object does not support item assignment”)有时你想要得到一个有序的整数列表,所以range() 看上去是生成此列表的不错方式。然而,你需要记住range() 返回的是“range object”,而不是实际的list 值。

3. 解决方法:

将上面例子的代码: a = range(0,N)改为a = list(range(0,N)) 就好啦!

你可能感兴趣的:(Python)