vectorsum.py#!/usr/bin/env/pythonimport sysfrom datetime import datetimeimport 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() - startprint ("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处理方法
原文地址:https://www.cnblogs.com/master-road/p/10646590.html
时间: 2024-10-18 02:20:00