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
尝试使用range()
创建整数列表(导致“TypeError: ‘range’ object does not support item assignment”)有时你想要得到一个有序的整数列表,所以range() 看上去是生成此列表的不错方式。然而,你需要记住range() 返回的是“range object”,而不是实际的list 值。
将上面例子的代码: a = range(0,N)改为a = list(range(0,N)) 就好啦!