TypeError: 'range' object does not support item assignment处理方法
Posted master-road
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了TypeError: 'range' object does not support item assignment处理方法相关的知识,希望对你有一定的参考价值。
vectorsum.py
#!/usr/bin/env/python
import sys
from datetime import datetime
import numpy as np
# def numpysum(n):
# a = np.arange(n) ** 2
# b = np.arange(n) ** 3
# c = a + b
# return c
def pythonsum(n):
a = range(n)
b = range(n)
c = []
for i in range(len(a)):
a[i] = i ** 2
b[i] = i ** 3
c.append(a[i] + b[i])
return c
size = int(sys.argv[1])
print (size)
start = datetime.now()
c = pythonsum(size)
delta = datetime.now() - start
print ("The last 2 elements of the sum", c[-2:])
print ("PythonSum elapsed time in microseconds", delta.microseconds)
# start = datetime.now()
# c = numpysum(size)
# delta = datetime.now() - start
# print ("The last 2 elements of the sum", c[-2:])
# print ("NumPySum elapsed time in microseconds", delta.microseconds)
----------------------------------------------------------------------------
运行结果:
D:\>python vectorsum.py 1000
1000
Traceback (most recent call last):
File "vectorsum.py", line 26, in <module>
c = pythonsum(size)
File "vectorsum.py", line 17, in pythonsum
a[i] = i ** 2
TypeError: ‘range‘ object does not support item assignment
----------------------------------------------------------------------------------------
将pythonsum函数修改如下:
def pythonsum(n):
a = list(range(n))
b = list(range(n))
c = []
for i in range(len(a)):
a[i] = i ** 2
b[i] = i ** 3
c.append(a[i] + b[i])
return c
运行正常,通过
-----------------------------------------------------------
以上是关于TypeError: 'range' object does not support item assignment处理方法的主要内容,如果未能解决你的问题,请参考以下文章
报错TypeError: Cannot read property 'range' of null
TypeError: 'list' object cannot be interpreted as an integer
TypeError: 'str' object is not callable
Python_报错:TypeError: file must have 'read' and 'readline' attributes