码迷,mamicode.com
首页 > 其他好文 > 详细

TypeError: 'range' object does not support item assignment处理方法

时间:2019-04-03 09:26:50      阅读:460      评论:0      收藏:0      [点我收藏+]

标签:font   ret   sum函数   nump   assign   argv   mos   sig   vector   

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处理方法

标签:font   ret   sum函数   nump   assign   argv   mos   sig   vector   

原文地址:https://www.cnblogs.com/master-road/p/10646590.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!